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 our GitHub code review bot spots this issue in your pull request it gives this advice:

django-doctorbotsuggested changes just now
helpers.py
1
+
def trigger_task(queryset):
2
+
    if queryset.count() > 0:

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
Suggested changes
-
    if queryset.count() > 0:
+
    if queryset.exists():
Commit suggestion
3
+
        trigger_tasks(queryset)
Update helpers.py

Instantly check if you have this issue for free

    Works with tools you use

    Read about how it works.