SQLAlchemy multiple foreign keys in one mapped class to the same primary key

后端 未结 2 711
闹比i
闹比i 2020-11-29 00:52

Am trying to setup a postgresql table that has two foreign keys that point to the same primary key in another table.

When I run the script I get the error

2条回答
  •  甜味超标
    2020-11-29 01:14

    The latest documentation:

    • http://docs.sqlalchemy.org/en/latest/orm/join_conditions.html#handling-multiple-join-paths

    The form of foreign_keys= in the documentation produces a NameError, not sure how it is expected to work when the class hasn't been created yet. With some hacking I was able to succeed with this:

    company_id = Column(Integer, ForeignKey('company.id'), nullable=False)
    company = relationship("Company", foreign_keys='Stakeholder.company_id')
    
    stakeholder_id = Column(Integer, ForeignKey('company.id'), nullable=False)
    stakeholder = relationship("Company",
                                foreign_keys='Stakeholder.stakeholder_id')
    

    In other words:

    … foreign_keys='CurrentClass.thing_id')
    

提交回复
热议问题