In cases where you want to append to querysets but want an empty one to begin with
Similar to conditions where we instantiate an empty list to begin with but gradually keep appending meaningful values to it
example..
def get_me_queryset(conditionA, conditionB, conditionC):
queryset = Model.objects.none()
if conditionA:
queryset |= some_complex_computation(conditionA)
elif conditionB:
queryset |= some_complex_computation(conditionB)
if conditionC:
queryset |= some_simple_computation(conditionC)
return queryset
get_me_queryset
should almost always return instance of django.db.models.query.QuerySet
(because good programming) and not None
or []
, or else it will introduce headaches later..
This way even if none of the conditions come True
, your code will still remain intact. No more type checking
For those who do not undestand |
operator's usage here:
queryset |= queryset2
It translates to:
queryset = queryset + queryset