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?
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()]))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With