我按照question中的建议,但我仍然收到此错误:
sqlalchemy.exc.NoForeignKeysError: Can't find any foreign key relationships between 'investment' and 'real_estate'.
模型
class Investment(db.Model):
__tablename__ = 'investment'
__mapper_args__ = {'polymorphic_identity': 'investment'}
id = Column(db.Integer, primary_key=True)
item_name = Column(db.String(64))
investment_type = Column(db.String(32), nullable=False)
__mapper_args__ = {'polymorphic_on': investment_type}
class RealEstate(Investment):
__tablename__ = 'real_estate'
__mapper_args__ = {'polymorphic_identity': 'real_estate'}
id = Column(db.Integer, primary_key=True)
current_balance = Column(db.Float)
我还更新了该答案中的示例,以反映SQLAlchemy的文档中的更改,但仍然是错误。
这里的目标是我不希望RealEstate继承的属性在投资表中。我想使用RealEstate表继承并保留所有这些属性。
谁能看到我错过的东西?
答案 0 :(得分:3)
RealEstate中的id
属性必须是引用Investment的外键。否则,你怎么能说每个RealEstate都是投资?
将RealEstate类定义更改为以下内容:
class RealEstate(Investment):
__tablename__ = 'real_estate'
__mapper_args__ = {'polymorphic_identity': 'real_estate'}
# This id below should reference Investment. Hence, define it as foreign key.
id = Column(Integer, ForeignKey('investment.id'), primary_key=True)
current_balance = Column(db.Float)