Django: how to check if Q object is empty?

Viewed 2523

I am chaining nodes to a Q object the following way:

q = Q()
for filter in filters:
    if filter_applies(filter):
        q.add(Q(some_criteria), Q.OR)

What means the q object might or might not have been chained a node. Later on I am trying to apply the q object in a filter, but only if this is not empty:

if q.not_empty():
    some_query_set.filter(q)

How can I check that q is not the same than it was when defined?

2 Answers

An empty Q object is falsy (bool(Q()) evaluates to False), so I think you should just check it that way:

if q:
    some_query_set.filter(q)

You shouldn't be checking if the length == 0, since that expression costs more.

Related