2011-10-17 82 views
7

可以说我有2款车型,DocumentPersonDocument通过“owner”属性与Person有关系。现在:如何通过SqlAlchemy中的连接表进行筛选?

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

将增加一倍,连接表Person。一个人表格将被选中,并且加倍的表格将被过滤,这不完全是我想要的,因此文档行不会被过滤。

我能做些什么就joinloaded表/模型应用过滤器?

回答

14

你是对的,表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) 
     ) 

这将返回正确的行,尽管它仍然必须Person表2个引用(连接)。您查询的真正解决方案是使用contains_eager代替joinedload

qry = (session.query(Document). 
     join(Document.owner). # THIS IS STILL IMPORTANT 
     options(contains_eager(Document.owner)). 
     filter(Person.is_deleted != True) 
     ) 
相关问题