[英]Query to check if size of collection is 0 or empty in SQLAlchemy?
Person
has one Building
. Person
有一Building
。
Person
has many Group
Person
有很多Group
I want to return all of the people
from a certain building
who do not have any Group
in their groups
collection. 我想回到所有的
people
从某building
没有任何谁Group
在他们的groups
集合。
Maybe I can search by people who have a group list that has a length of 0? 也许我可以搜索拥有长度为0的组列表的人? Something like:
就像是:
unassigned=Person.query.filter(Person.building==g.current_building,Person.groups.any()).all()
First count the groups per building, then filter on that count. 首先计算每个建筑物的群组,然后对该计数进行过滤。
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()
If you need to know if a relation have records after the query use the count()
method on the relation: 如果在查询后需要知道关系是否有记录,请在关系上使用
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.