Django: show me the SQL
Here are 8 different ways of inspecting the SQL generated by the ORM of Django.
- Using the
query
attribute - Using
connection.queries
- In the logs
- Using
CaptureQueriesContext
- Using Django Debug Toolbar
- Using Django Debug Toolbar and debugsqlshell
- Using django-extensions and shell_plus
- Using django-extensions and runserver_plus
Using the query
attribute
Add .query
to your queryset. For example:
qs = User.objects.filter(username="gustave")
print(qs.query)
Note: this does not work for the expressions that do not return a QuerySet. For example, those ending with .count()
or .exists()
.
Using connection.queries
- In your Django settings make sure
DEBUG
is set toTrue
- In your code do:
from django.db import connection, reset_queries
# reset_queries() # Optional, will empty the query list
print(connection.queries)
Official documentation: here
In the logs
Add a django.db.backends
logger at the level DEBUG
in settings.py
.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django.db.backends': {
'handlers': ['console'],
'level': 'DEBUG',
},
},
}
Tip: add debug log in your code to find where SQL is coming from. The logs
Using CaptureQueriesContext
from django.db import connection
from django.test.utils import CaptureQueriesContext
with CaptureQueriesContext(connection) as ctx:
# your code here
print(ctx.captured_queries)
Thanks to Seb for pointing out that solution to me.
Using Django Debug Toolbar
The initial effort to install the toolbar is a bit higher than the other methods. But when working on a website, this is a must have.
- Install it following the instructions here
- Open the page you want to inspect in your browser and check out the "SQL" section.
Using Django Debug Toolbar and debugsqlshell
- Install it following the instructions here
./manage.py debugsqlshell
- In the shell do a query, for example:
User.objects.count()
This method also display the time the query took to be executed which can be useful.
Official documentation: here
Thanks to Tim for pointing out that solution to me.
Using django-extensions and shell_plus
python -m pip install django-extensions
./manage.py shell_plus --print-sql
- In the shell do a query, for example:
User.objects.count()
Official documentation: here
Using django-extensions and runserver_plus
python -m pip install django-extensions Werkzeug
./manage.py runserver_plus --print-sql
- Do some HTTP requests and look in the logs for the SQL generated
- Killer feature: you can also pass the argument
--print-sql-location
and a stacktrace will be added to each SQL query to help you find from where it is coming.
Those parameters are not officially documented, but do exist in the code.