There is only one truth. It is the source.

Seeing Django ORM generated SQL

April 24, 2015

Tags: django, sql

There are 2 ways to see the what SQL is generated by Django's ORM.

  1. Print the query attribute of a queryset. This will print the queryset as a SQL statement, but note that not all interpolated values will be represented correctly. Strings for example will not have quotation marks around them which means that if you try to run this statement in your database shell, it may not work.
In [1]: print User.objects.all().query
SELECT `auth_user`.`id`, `auth_user`.`password`, `auth_user`.`last_login`,  `auth_user`.`email`, `auth_user`.`first_name`, `auth_user`.`last_name`, `auth_user`.`is_active`, `auth_user`.`is_staff`, `auth_user`.`is_superuser`, `auth_user`.`date_joined` FROM `auth_user` ORDER BY `auth_user`.`email` ASC
  1. Log the generate SQL from the database driver. This will print the exact SQL the database driver sent to the database. Because this is the full SQL statement, you can use this statement 100% of the time in your database shell.
In [1]: import logging

In [2]: l = logging.getLogger('django.db.backends')

In [3]: l.setLevel(logging.DEBUG)

In [4]: l.addHandler(logging.StreamHandler())

In [5]: User.objects.all()
(0.000) SET SQL_AUTO_IS_NULL = 0; args=None
DEBUG:django.db.backends:(0.000) SET SQL_AUTO_IS_NULL = 0; args=None
(0.046) SELECT `auth_user`.`id`, `auth_user`.`password`, `auth_user`.`last_login`,  `auth_user`.`email`, `auth_user`.`first_name`, `auth_user`.`last_name`, `auth_user`.`is_active`, `auth_user`.`is_staff`, `auth_user`.`is_superuser`, `auth_user`.`date_joined` FROM `auth_user` ORDER BY `auth_user`.`email` ASC LIMIT 21; args=()
Out[5]: [<User: ...>, ...]