Table(Model) Inheritance with Flask SQLAlchemy

試著忘記壹切 提交于 2019-12-22 05:50:11

问题


I followed the advice in this question but I'm still receiving this error: sqlalchemy.exc.NoForeignKeysError: Can't find any foreign key relationships between 'investment' and 'real_estate'.

Models

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)

I also updated the examples in that answer to reflect changes in SQLAlchemy's docs but, still, the error.

The goal here is that I don't want the attributes inherited by RealEstate to be in the Investment table. I would like to inherit and retain all of these attributes with the RealEstate table.

Can anyone see what I missed?


回答1:


The id attribute in RealEstate must be a foreign key referencing the Investment. Otherwise, how can you say that every RealEstate is an investment ?

Change your RealEstate class definition to the following:

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)


来源:https://stackoverflow.com/questions/25189017/tablemodel-inheritance-with-flask-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!