我刚开始使用Flask-SqlAlchemy项目,并且在使用外键时遇到了一些麻烦。
我有表用户和投资组合。 Portfolio使用用户名为用户提供外键。我像这样建立我的模型。
permalink: /whatever/
我尝试运行简单的全选查询时得到的错误是:
class User(db.Model):
__tablename__ = 'portfolio_users'
__table_args__ = {"schema":"keldan"}
username = Column(String(), primary_key=True)
date_added = Column(DateTime())
class Portfolio(db.Model):
__tablename__ = 'portfolios'
__table_args__ = {"schema":"keldan"}
id = Column('pid', Integer(), Sequence('portfolios_pid_seq'), primary_key=True)
date_added = Column(DateTime())
name = Column(String())
username = Column(String(), ForeignKey('portfolio_users.username'))
user = relationship('User', backref=backref('portfolios', cascade='save-update, merge, delete, delete-orphan'))
这些表是这样创建的:
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'portfolios.username' could not find table 'portfolio_users' with which to generate a foreign key to target column 'username'
我花了大部分时间试图解决这个问题,或者使用primaryjoin制作变通方法,但似乎没有任何工作。
答案 0 :(得分:3)
我终于找到了我正在寻找的答案here
如果您没有使用默认架构(公共),那么它不足以为每个类指定架构,但我也需要在外键中指定它。
username = Column(String(), ForeignKey('keldan.portfolio_users.username'))