2015-12-09 91 views
2

什麼是最好的方式檢索一個表中的所有行(這是多對多的一部分)與多個孩子?我曾嘗試過:SQLAlchemy多對多篩選兒童人數

session.query(Parent).filter(len(Parent.children)>1).all() 

但我得到錯誤'對象類型'InstrumentedAttribute'沒有len()'。我已經能夠得到所有家長使用至少有一個孩子:

session.query(Parent).filter(Parent.children).all() 

回答

4

使用having()

from sqlalchemy import func 

session.query(Parent).\ 
     join(Parent.children).\ 
     group_by(Parent).\ 
     having(func.count(Child.id) > 1)