8

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

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

This did not work for me, the only way I could create the table without getting an error was by changing the id column to the following: id = db.Column(db.Integer, primary_key=True, default=lambda: uuid.uuid4().hex). If anybody comes across this comment and can tell me why, even with the code exactly as above I was unable to generate a primary key without that default, please let me know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.