如何在SQLAlchemy中为同一个表定义两个关系

时间:2011-09-25 19:31:05

标签: python sql sqlalchemy relationship

我查看了SQLAlchemy教程和其他类似的问题,但我似乎很难让这个联接起作用:

方案:我有一个由pages模型表示的Page表。页面可以由用户创建并由用户编辑,但不一定是相同的。我的Page模型看起来像这样(删节):

class Page(Base):
    __tablename__ = 'pages'

    id = Column(Integer, primary_key = True)
    slug = Column(Text)
    title = Column(Text)
    direct_link = Column(Text)
    body = Column(Text)
    category_id = Column(Integer, ForeignKey('categories.id'))
    published_on = Column(DateTime)
    publishing_user_id = Column(Integer, ForeignKey('users.id'))
    last_edit_on = Column(DateTime)
    last_edit_user_id = Column(Integer, ForeignKey('users.id'))

    # 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")
    category = relationship('Category', backref = backref('pages', order_by = id))

我的用户存储在User模型所代表的用户表中。正如我所说的那样,我一直在寻找SQLAlchemy文档,我试图让它看起来尽可能与它们的例子类似,但是没有用。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:12)

从版本0.8开始,SQLAlchemy可以仅使用foreign_keys关键字参数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])

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

上的文档

答案 1 :(得分:7)

我认为你几乎做对了;在定义Model时,您应该使用Table名称来代替primaryjoin名称。而不是

# 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")

使用:

# 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")

答案 2 :(得分:2)

尝试foreign_keys选项:

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)