我有三个表:用户,基金和基金类型。每个基金都有一个基金类型,每个用户都有一个基金列表,每个用户也可以拥有他们创建的基金类型列表。
架构:
class Fund(Base):
__tablename__ = 'fds_funds'
fds_fund_id = Column(Integer, primary_key=True)
fds_name = Column(String(128))
fds_symbol = Column(String(5))
fds_fdt_fund_type_id = Column(Integer, ForeignKey('fdt_fund_type_id'))
fund_type = relationship('FundType', backref=backref('fds_funds', uselist=False))
class FundType(Base):
__tablename__ = 'fdt_fund_types'
fdt_fund_type_id = Column(Integer, primary_key=True)
fdt_type_name = Column(String(128))
fdt_usr_user_id = Column(Integer, ForeignKey('usr_user_id'), nullable=True)
user_funds = Table('usf_user_funds', Base.metadata,
Column('usf_usr_user_id', Integer, ForeignKey('usr_users.usr_user_id')),
Column('usf_fds_fund_id', Integer, ForeignKey('fds_funds.fds_fund_id'))
)
class User(Base):
"""
Application's user model.
"""
__tablename__ = 'usr_users'
usr_user_id = Column(Integer, primary_key=True)
usr_email = Column(Unicode(50))
_usr_password = Column('password', Unicode(64))
fund_types = relationship('FundType', foreign_keys='FundType.fdt_usr_user_id')
funds = relationship('Fund', secondary=user_funds)
我正在关注文档here,并且似乎非常明确地说外键指定的第一个参数应该是列名,而不是表名,但是我在收到此错误时我运行initialize_DB脚本:
sqlalchemy.exc.NoReferencedTableError:与列'fdt_fund_types.fdt_usr_user_id'关联的外键找不到表 'usr_user_id'用于生成目标列的外键 '无'
我误读了文档吗?
答案 0 :(得分:0)
我不确定是什么修复它,但我做了一些重新安排和搞乱参考。对于后代,这有效:
user_funds = Table('usf_user_funds', Base.metadata,
Column('usf_usr_user_id', Integer, ForeignKey('usr_users.usr_user_id')),
Column('usf_fds_fund_id', Integer, ForeignKey('fds_funds.fds_fund_id'))
)
class User(Base):
"""
Application's user model.
"""
__tablename__ = 'usr_users'
usr_user_id = Column(Integer, primary_key=True)
usr_email = Column(Unicode(50))
_usr_password = Column('password', Unicode(64))
fund_types = relationship('FundType', foreign_keys='FundType.fdt_usr_user_id')
funds = relationship('Fund', secondary=user_funds)
class FundType(Base):
__tablename__ = 'fdt_fund_types'
fdt_fund_type_id = Column(Integer, primary_key=True)
fdt_type_name = Column(String(128))
fdt_usr_user_id = Column(Integer, ForeignKey('usr_users.usr_user_id'), nullable=True)
class Fund(Base):
__tablename__ = 'fds_funds'
fds_fund_id = Column(Integer, primary_key=True)
fds_name = Column(String(128))
fds_symbol = Column(String(5))
fds_fdt_fund_type_id = Column(Integer, ForeignKey('fdt_fund_types.fdt_fund_type_id'))
fund_type = relationship('FundType', backref=backref('funds', uselist=False))