如何在 SQLAlchemy 中定义同一个表的两个关系 [英] How to define two relationships to the same table in SQLAlchemy

查看:75
本文介绍了如何在 SQLAlchemy 中定义同一个表的两个关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经查看了 SQLAlchemy 教程和其他类似问题,但我似乎很难让这个加入工作:

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

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

The scenario: I have a pages table represented by the Page model. Pages can be created by an user and edited by an user, but not necessarily the same one. My Page model looks like this (abridged):

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 模型表示的 users 表中.正如我所说,我一直在寻找这个 SQLAlchemy 文档,我试图让它看起来尽可能类似于他们的示例,但无济于事.任何帮助将不胜感激.

My users are stored in the users table represented by the User model. As I said I’ve been all over the SQLAlchemy docs looking for this, I’ve tried to make it look as similar to their example as possible, but no to no avail. Any help would be greatly appreciated.

推荐答案

从 0.8 版本开始,SQLAlchemy 可以仅使用 foreign_keys 关键字参数到 relationship 来解决歧义连接.

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])

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

这篇关于如何在 SQLAlchemy 中定义同一个表的两个关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆