Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table(Model) Inheritance with Flask SQLAlchemy

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?

like image 258
frankV Avatar asked Aug 07 '14 17:08

frankV


1 Answers

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)
like image 51
codegeek Avatar answered Oct 25 '22 00:10

codegeek