[英]Query to check if size of collection is 0 or empty in SQLAlchemy?
Person
有一Building
。
Person
有很多Group
我想回到所有的people
從某building
沒有任何誰Group
在他們的groups
集合。
也許我可以搜索擁有長度為0的組列表的人? 就像是:
unassigned=Person.query.filter(Person.building==g.current_building,Person.groups.any()).all()
使用否定( ~
)與any
:
q = session.query(Person)
q = q.filter(Person.building == g.current_building)
q = q.filter(~Person.groups.any())
any
比你需要的更強大,但它會做得很好。
首先計算每個建築物的群組,然后對該計數進行過濾。
gc = session.query(
Person.id,
db.func.count(Group.id).label('gc')
).join(Person.groups).group_by(Person.id).subquery()
unassigned = session.query(Person).join(
(gc, gc.c.person_id == Person.id)
).filter(
Person.building == g.current_building,
gc.c.gc == 0
).all()
如果在查詢后需要知道關系是否有記錄,請在關系上使用count()
方法:
persons = session.query(Person).filter(Person.building == g.current_building).all()
for p in persons:
if p.groups.count():
print("%s have groups" % p)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.