Checking for empty queryset in Django

DjangoDjango Queryset

Django Problem Overview


What is the recommended idiom for checking whether a query returned any results?
Example:

orgs = Organisation.objects.filter(name__iexact = 'Fjuk inc')
# If any results
    # Do this with the results without querying again.
# Else, do something else...

I suppose there are several different ways of checking this, but I'd like to know how an experienced Django user would do it. Most examples in the docs just ignore the case where nothing was found...

Django Solutions


Solution 1 - Django

if not orgs:
    # Do this...
else:
    # Do that...

Solution 2 - Django

Since version 1.2, Django has QuerySet.exists() method which is the most efficient:

if orgs.exists():
    # Do this...
else:
    # Do that...

But if you are going to evaluate QuerySet anyway it's better to use:

if orgs:
   ...

For more information read QuerySet.exists() documentation.

Solution 3 - Django

If you have a huge number of objects, this can (at times) be much faster:

try:
    orgs[0]
    # If you get here, it exists...
except IndexError:
    # Doesn't exist!

On a project I'm working on with a huge database, not orgs is 400+ ms and orgs.count() is 250ms. In my most common use cases (those where there are results), this technique often gets that down to under 20ms. (One case I found, it was 6.)

Could be much longer, of course, depending on how far the database has to look to find a result. Or even faster, if it finds one quickly; YMMV.

EDIT: This will often be slower than orgs.count() if the result isn't found, particularly if the condition you're filtering on is a rare one; as a result, it's particularly useful in view functions where you need to make sure the view exists or throw Http404. (Where, one would hope, people are asking for URLs that exist more often than not.)

Solution 4 - Django

To check the emptiness of a queryset:

if orgs.exists():
    # Do something

or you can check for a the first item in a queryset, if it doesn't exist it will return None:

if orgs.first():
    # Do something

Solution 5 - Django

The most efficient way (before django 1.2) is this:

if orgs.count() == 0:
    # no results
else:
    # alrigh! let's continue...

Solution 6 - Django

I disagree with the predicate

if not orgs:

It should be

if not orgs.count():

I was having the same issue with a fairly large result set (~150k results). The operator is not overloaded in QuerySet, so the result is actually unpacked as a list before the check is made. In my case execution time went down by three orders.

Solution 7 - Django

You could also use this:

if(not(orgs)): #if orgs is empty else: #if orgs is not empty

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNiklasView Question on Stackoverflow
Solution 1 - DjangoAdamView Answer on Stackoverflow
Solution 2 - DjangoLeonid ShvechikovView Answer on Stackoverflow
Solution 3 - DjangoAdam PlayfordView Answer on Stackoverflow
Solution 4 - DjangoTuss4View Answer on Stackoverflow
Solution 5 - DjangoBartoszView Answer on Stackoverflow
Solution 6 - DjangohedleyroosView Answer on Stackoverflow
Solution 7 - DjangoRupesh ChaudhariView Answer on Stackoverflow