如何通过SqlAlchemy中的joinloaded表进行过滤?

时间:2011-10-17 12:38:17

标签: python sqlalchemy

假设我有2个模型,DocumentPersonDocument通过“所有者”属性与Person建立了关系。现在:

session.query(Document)\
    .options(joinedload('owner'))\
    .filter(Person.is_deleted!=True)

将加倍表Person。将选择一个人表,并且将对双倍表进行过滤,这不是我想要的,因为这样文档行不会被过滤。

如何在joinloaded table / model上应用过滤器?

1 个答案:

答案 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)
        )