How to define two relationships to the same table in SQLAlchemy

前端 未结 3 1364
日久生厌
日久生厌 2020-12-31 00:16

I’ve looked all over the SQLAlchemy tutorial and other similar questions but I seem to be struggling to get this join to work:

The scenario: I have

相关标签:
3条回答
  • 2020-12-31 00:31

    As of version 0.8, SQLAlchemy can resolve the ambiguous join using only the foreign_keys keyword parameter to relationship.

    publish_user = relationship(User, foreign_keys=[publishing_user_id],
                                      backref=backref('pages', order_by=id))
    edit_user = relationship(User, foreign_keys=[last_edit_user_id])
    

    Documentation at http://docs.sqlalchemy.org/en/rel_0_9/orm/join_conditions.html#handling-multiple-join-paths

    0 讨论(0)
  • 2020-12-31 00:33

    I think you almost got it right; only instead of Model names you should use Table names when defining primaryjoin. So instead of

    # Define relationships
    publish_user = relationship('User', backref = backref('pages', order_by = id), 
        primaryjoin = "Page.publishing_user_id == User.id")
    edit_user = relationship('User', 
        primaryjoin = "Page.last_edit_user_id == User.id")
    

    use:

    # Define relationships
    publish_user = relationship('User', backref = backref('pages', order_by = id), 
        primaryjoin = "pages.publishing_user_id == users.id")
    edit_user = relationship('User', 
        primaryjoin = "pages.last_edit_user_id == users.id")
    
    0 讨论(0)
  • 2020-12-31 00:35

    Try foreign_keys option:

    publish_user = relationship(User, foreign_keys=publishing_user_id,
                                      primaryjoin=publishing_user_id == User.id,
                                      backref=backref('pages', order_by=id))
    edit_user = relationship(User, foreign_keys=last_edit_user_id,
                                   primaryjoin=last_edit_user_id == User.id)
    
    0 讨论(0)
提交回复
热议问题