假设我有2个模型,Document
和Person
。 Document
通过“所有者”属性与Person
建立了关系。现在:
session.query(Document)\
.options(joinedload('owner'))\
.filter(Person.is_deleted!=True)
将加倍表Person
。将选择一个人表,并且将对双倍表进行过滤,这不是我想要的,因为这样文档行不会被过滤。
如何在joinloaded table / model上应用过滤器?
答案 0 :(得分:17)
你说得对,表Person
将在结果SQL
中使用两次,但每个表都有不同的用途:
filter(Person.is_deleted != True)
options(joinedload('owner'))
但是您的查询返回错误结果的原因是因为您的过滤条件不完整。为了使其产生正确的结果,您还需要加入两个模型:
qry = (session.query(Document).
join(Document.owner). # THIS IS IMPORTANT
options(joinedload(Document.owner)).
filter(Person.is_deleted != True)
)
这将返回正确的行,即使它仍然有2个引用(JOIN)到Person
表。您查询的真正解决方案是使用contains_eager代替joinedload:
qry = (session.query(Document).
join(Document.owner). # THIS IS STILL IMPORTANT
options(contains_eager(Document.owner)).
filter(Person.is_deleted != True)
)