Comparing queryset.count() instead of checking queryset.exists()

Comparing queryset.count() is less efficient than checking queryset.exists(), so use querySet.count() if you only want the count, and use queryset.exists() if you only want to find out if at least one result exists.

queryset.count() performs an SQL operation that scans every row in the database table. queryset.exists() simply reads a single record in the most optimized way (removing ordering, clearing any user-defined select_related(...) or distinct(...).

This is especially relevant for Postgres because count() can be very expensive.

If we spot this issue in your GitHub pull request we give this advice:

helpers.pyperformancemedium
def trigger_task(queryset):
-
    if queryset.count() > 0:
+
    if queryset.exists():
        trigger_tasks(queryset)

Comparing queryset.count() is less efficient than checking queryset.exists(), so use querySet.count() if you only want the count, and use queryset.exists() if you only want to find out if at least one result exists.

Read more
Protect your pull requests from over 40 types of common Django technical debts with our GitHub code review bot.

Configuring this check

Django Doctor will run this check by default. No configuration is needed but the check can be turned on/off using check code count-instead-exists in your pyproject.toml file.

Read more about configuring Django Doctor.