+ +

Django: show me the SQL

+ +
+
+
+ +
+
+
+ +
+
+
+
+ + +

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

+
    +
  1. Using the query attribute
  2. +
  3. Using connection.queries
  4. +
  5. In the logs
  6. +
  7. Using Django Debug Toolbar
  8. +
  9. Using django-extensions and shell_plus
  10. +
  11. Using django-extensions and runserver_plus
  12. +
+

Using the query attribute

+
    +
  1. Add .query to your queryset. For example:
  2. +
+
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. +
  3. In your code do:
  4. +
+
from django.db import connection, reset_queries
+# reset_queries() # Optional, will empty the query list
+print(connection.queries)
+
+ +

Official documentation: here

+

In the logs

+
    +
  1. Add a django.db.backends logger at the level DEBUG in settings.py.
  2. +
+
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.

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

TODO add pic

+

Using django-extensions and shell_plus

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

Official documentation: here

+

Using django-extensions and runserver_plus

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

Those parameters are not officially documented, but do exist in the code.

+
+ +
+
+
+
+ +
+