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.

So in practice, do this

def check_hounds():
    queryset = HoundsModel.objects.all()
    if queryset.exists():
         return "oh no. Run!"

Instead of this

def check_hounds():
    queryset = HoundsModel.objects.all()
    if queryset:
         return "oh no. Run!"

Are you affected? Check with
pip install django-doctor

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 truthy-instead-exists in your pyproject.toml file.

Read more about configuring Django Doctor.