Table (Model) SQLAlchemy Flask Inheritance

I followed advice in this question , but I still get 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 this answer to reflect the changes in the SQLAlchemy docs, but nonetheless an error.

goal is that I do not want the attributes inherited by RealEstate to be in the investment table. I would like to inherit and store all of these attributes in a RealEstate table.

Can anyone see what I missed?

+3
source share
1 answer

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

Change the definition of the RealEstate class 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) 
+2
source

Source: https://habr.com/ru/post/947146/


All Articles