Checking queryset truthiness instead of checking queryset.exists()

This can load every row in the database table into memory because the queryset is evaluated. Checking if a queryset is truthy/falsey is much less efficient than checking queryset.exists().

Querysets are lazy, so do not do database reads until the data is interacted with by the code. Checking truthiness evaluates the queryset, and reads every row in the queryset in one go - loading all of them into memory.

This is especially inefficient if the table is very large: it can cause a CPU spike on the database and use a lot of memory on the web server. So instead of pulling every single row from the table, check queryset.exists(), which simply tries to read a single record from the table in a very efficient way.

If our GitHub code review bot spots this issue in your pull request it gives this advice:

django-doctorbotsuggested changes just now
tasks.py
1
+
if queryset:
Suggested changes
-
if queryset:
+
if queryset.exists():
Commit suggestion

This can load every row in the database table into memory because the queryset is evaluated. Checking if a queryset is truthy/falsey is much less efficient than checking queryset.exists().

Read more
2
+
    trigger_tasks(queryset)
Update tasks.py
We're your Django code review copilot. Get code improvements right in your pull request with our GitHub code review bot.

Configuring this check

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

Read more about configuring Code Review Doctor.