简体   繁体   中英

Query to check if size of collection is 0 or empty in SQLAlchemy?

Person has one Building .

Person has many Group

I want to return all of the people from a certain building who do not have any Group in their groups collection.
Maybe I can search by people who have a group list that has a length of 0? Something like:

unassigned=Person.query.filter(Person.building==g.current_building,Person.groups.any()).all()

Use negation ( ~ ) with 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.

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:

persons = session.query(Person).filter(Person.building == g.current_building).all()
for p in persons:
    if p.groups.count():
        print("%s have groups" % p)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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