Django: show me the SQL
+ + + + +Here are 6 different ways of inspecting the SQL generated by the ORM of Django.
+-
+
- Using the
query
attribute
+ - Using
connection.queries
+ - In the logs +
- Using Django Debug Toolbar +
- 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 levelDEBUG
insettings.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 Django Debug Toolbar
+The initial effort to install the toolbar is a bit higher than the other method. 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. +
TODO add pic
+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.
+ + + + ++