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

kos*_*kot 8 python sqlalchemy

可以说我有2个型号,Document而且Person.DocumentPerson"所有者"财产有关系.现在:

session.query(Document)\
    .options(joinedload('owner'))\
    .filter(Person.is_deleted!=True)
Run Code Online (Sandbox Code Playgroud)

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

如何在joinloaded表/模型上应用过滤器?

van*_*van 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)
        )
Run Code Online (Sandbox Code Playgroud)

这将返回正确的行,即使它仍然有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)
        )
Run Code Online (Sandbox Code Playgroud)