【发布时间】: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