【问题标题】:SQLAlchemy: Can't join m2mSQLAlchemy:无法加入 m2m
【发布时间】:2021-09-21 23:28:32
【问题描述】:

我有两个模型,分别称为 Items 和 Privileges。它们之间用m2m表定义了关系:

class Privilege(Archiveable):
    __tablename__ = 'privileges'
    id = Column(Integer, primary_key=True)
    items = relationship('Item', secondary='privileges_have_items', back_populates='privileges', lazy='raise')
    ....

class Item(Archiveable):
    __tablename__ = 'items'
    id = Column(Integer, primary_key=True)
    privileges = relationship('Privilege', secondary='privileges_have_items', back_populates='items', lazy='raise')
    ....

我正在尝试像这样加入两个表(实体类型 = 项目类):

allowed_entities_query = select(entity_type).options(join(entity_type, Privilege))

但我仍然得到: sqlalchemy.exc.NoForeignKeysError: Can't find any foreign key relationships between 'items' and 'privileges'. 虽然上面已经明确定义了它们。我需要定义一个 on 子句吗?这似乎很奇怪,因为我已经定义了他们的关系。 joinload 确实有效,但我只想在以下情况下加入:.where(Privilege.id.in_(filtered_privileges_ids)) 并且我读到我需要使用.filter 执行.join 我怎样才能做到这一点?

感谢任何帮助,因为文档似乎非常缺乏或很难找到(请注意,我正在使用新的 API)

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    我不确定您为什么使用options 构造。我认为查询应该在select 语句中使用join 即可工作:

    allowed_entities_query = select(entity_type).join(entity_type.privileges)
    

    ,或更明确地说:

    allowed_entities_query = select(entity_type).join(Privileges, entity_type.privileges)
    

    Joins 的文档非常完善。

    【讨论】:

    • 我明白了。当我看到 1.4 和“查询”时,我认为它与旧的查询方法有关(我仍然不明白为什么文档不被称为 2.0,我是 sqlalchemy 的新手)。至于 .options,这就是我使用joinedload 的方式,因此我也可以将它用于.join。然后它也要求加入的右侧,这让我更加困惑。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 2018-01-03
    • 2019-04-29
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多