Debug Django SQL queries


What's inside this article ⌄
  • Debug connection queries debug
  • Debug queryset SQL logging
  • Debug shell query inspection
  • Debug lazy queryset testing

Suppose you came across a case where you have to understand what SQL queries Django fires. Yeah, you can intercept them on the database side of things somehow, but Django has a really handy tool for handling that.

For instance, you want to double-check that querysets are really work in a lazy fashion. The most convenient way to do this is to enter a Django shell we spoke about, then import connection object:

from django.db import connection

Then you can execute your Django operation and see what’s inside connection.queries:

queryset = CustomUser.objects.all()
print(connection.queries)
print(len(connection.queries)) # 0

connection.queries will give you a list of SQL queries, and len(connection.queries) obviously gives you a count.

In the case above, the output will be 0.

For example, if you execute queryset instead of assigning it to a variable, you end up with an actual SQL query fired:

CustomUser.objects.all() # without assigning to a variable
print(len(connection.queries)) # 1

So, you can optimize your app by trying different approaches and analyzing the SQL queries Django sends to the database.