Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: how to check if Q object is empty?

Tags:

python

django

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?

like image 667
dabadaba Avatar asked May 26 '17 09:05

dabadaba


2 Answers

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()]))
like image 189
Aamir Rind Avatar answered Oct 06 '22 10:10

Aamir Rind


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.

like image 39
jurms22 Avatar answered Oct 06 '22 08:10

jurms22