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:

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
Suggested changes
-
if queryset:
+
if queryset.exists():
Commit suggestion
2
+
    trigger_tasks(queryset)
Update tasks.py

Instantly check if you have this issue for free

    Works with tools you use

    Read about how it works.