SQLAlchemy:无法加入 m2m

SQLAlchemy: Can't join m2m

我有两个模型,分别称为项目和特权。它们之间定义了一个 m2m table:

的关系
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')
    ....

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

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 子句吗?这似乎很奇怪,因为我已经定义了他们的关系。 joinedload 确实有效,但我只想在以下情况下加入:.where(Privilege.id.in_(filtered_privileges_ids)) 然后我读到我需要用 .filter 做一个 .join 我怎样才能做到这一点?

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

我不确定您为什么要使用 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 都有很好的记录。