Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 299
Johnston Avatar asked Jan 14 '14 13:01

Johnston


People also ask

How do I check if a SQLAlchemy query is empty?

rowcount works for me, as a simple way of checking if a query is empty in SQLAlchemy.

How do I check if a Fetchall is empty?

fetchall() fetches all the rows of a query result. It returns all the rows as a list of tuples. An empty list is returned if there is no record to fetch.

What does all () do in SQLAlchemy?

all() method. The Query object, when asked to return full entities, will deduplicate entries based on primary key, meaning if the same primary key value would appear in the results more than once, only one object of that primary key would be present. This does not apply to a query that is against individual columns.

What does SQLAlchemy all () return?

As the documentation says, all() returns the result of the query as a list.


1 Answers

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.

like image 125
van Avatar answered Oct 13 '22 21:10

van