Django: exists() using queryset cache

Viewed 154

Does django's QuerySet.exists() method use the queryset's cache if called twice? For example

# this makes a call to db
queryset.exists()
# > true

# does it make a call to the db or reuse some cached result?
queryset.exists()
# > true

I know that len(queryset) won't make a call to the db if it has previously been evaluated. Is it the same with exists?

1 Answers

If you use .exists() twice, it will make two queries, the queryset will not cache the outcome of the .exists() call.

If you however plan to enumerate over the queryset, you can check the truthiness of the queryset with:

if queryset:
    # not empty
    pass
else:
    # empty
    pass

This will make a query and load the records into the cache of the queryset, so later enumerating over the queryset, applying len(…), etc. will not trigger a new query.

This however should be avoided if you are only interested to check if an item exists, for the same reason you should use .count() [Django-doc] over len(…) if you are only interested in the number of records: by using len(…) you load the records into memory, which is more expensive than making a SELECT COUNT(*) query.

Related