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:
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()
.
- | if queryset: |
+ | if queryset.exists(): |
2 | + | trigger_tasks(queryset) |