Search code examples
pythondjangodjango-queryset

Django: When to use QuerySet none()


Just came across this in the django docs

Calling none() will create a queryset that never returns any objects and no query will be executed when accessing the results. A qs.none() queryset is an instance of EmptyQuerySet.

I build a lot of CRUD apps (surprise) and I can't think of a situation where I would need to use none().

Why would one want to return an EmptyQuerySet?


Solution

  • 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()