Django: show me the SQL

Here are 8 different ways of inspecting the SQL generated by the ORM of Django.

  1. Using the query attribute
  2. Using connection.queries
  3. In the logs
  4. Using CaptureQueriesContext
  5. Using Django Debug Toolbar
  6. Using Django Debug Toolbar and debugsqlshell
  7. Using django-extensions and shell_plus
  8. 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

  1. In your Django settings make sure DEBUG is set to True
  2. 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.

  1. Install it following the instructions here
  2. Open the page you want to inspect in your browser and check out the "SQL" section.

Using Django Debug Toolbar and debugsqlshell

  1. Install it following the instructions here
  2. ./manage.py debugsqlshell
  3. 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

  1. python -m pip install django-extensions
  2. ./manage.py shell_plus --print-sql
  3. In the shell do a query, for example: User.objects.count()

Official documentation: here

Using django-extensions and runserver_plus

  1. python -m pip install django-extensions Werkzeug
  2. ./manage.py runserver_plus --print-sql
  3. Do some HTTP requests and look in the logs for the SQL generated
  4. 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.