Django: When To Use QuerySet None
Usually in instances where you need to provide a QuerySet
, but there isn't one to provide - such as calling a method or to give to a template.
The advantage is if you know there is going to be no result (or don't want a result) and you still need one, none()
will not hit the database.
For a non-realistic example, say you have an API where you can query your permissions. If the account hasn't been confirmed, since you already have the Account
object and you can see that account.is_activated
is False
, you could skip checking the database for permissions by just using Permission.objects.none()
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