2011-10-17 85 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) 
     ) 
相關問題