dabadaba
dabadaba

Reputation: 9532

Django: how to check if Q object is empty?

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?

Upvotes: 12

Views: 4175

Answers (2)

jurms22
jurms22

Reputation: 121

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.

Upvotes: 5

Aamir Rind
Aamir Rind

Reputation: 39689

If you want to check if q is empty or not you can check its length:

>>> q = Q()
>>> len(q)
0

Alternatively, you can first prepare a dict of filters to be applied:

lookups = {}
for filter in filters:
    if filter_applies(filter):
        lookups[filter] = some_criteria

Then you can check if its not empty apply filters using Q object:

import operator

if lookups:
    qs = qs.filter(reduce(operator.or_, [Q(f) for f in lookups.items()]))

Upvotes: 10

Related Questions