简体   繁体   English

查询以检查SQLAlchemy中集合的大小是0还是空?

[英]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()

Use negation ( ~ ) with any : 使用否定( ~ )与any

q = session.query(Person)
q = q.filter(Person.building == g.current_building)
q = q.filter(~Person.groups.any())

any is more powerful than needed in your case, but it will do the job just fine. any比你需要的更强大,但它会做得很好。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM