Show SQL queries

Posted: February 27th, 2010 | Author: | Filed under: Django | Tags: , , , | No Comments »

The Django ORM is just awesome but for debugging purposes it is usefull to be able to see what queries are actually made to the database. It is possible to have a history of all the queries made until the request is finished. Additionaly the query object can be accessed to retrieve the SQL statement.

Importing the connection and printing the queries

>>> from django.db import connection

>>> print connection.queries
[]
>>>  # as you can see it prints an empty list since no queries are made yet!

Make a call to the database and print again the queries

# I am using a model from my app. This is just an example.
>>> from apps.cobblers.models import Cobbler

>>> Cobbler.objects.filter()
[<Cobbler: 99 Dry Cleaners>]

>>> print connection.queries
[{'time': '0.000', 'sql': u'SELECT `cobblers_cobbler`.`id`, `cobblers_cobbler`.`name`, `cobblers_cobbler`.`description`, `cobblers_cobbler`.`address`, `cobblers_cobbler`.`city`, `cobblers_cobbler`.`post_code`, `cobblers_cobbler`.`telephone`, `cobblers_cobbler`.`email` FROM `cobblers_cobbler` ORDER BY `cobblers_cobbler`.`name` ASC LIMIT 21'}]
# the result is different, we have the latest query.

Finally it is also possible to see the query which will be executed for a given statement

>>> Cobbler.objects.filter(id=1).query
<django.db.models.sql.query.Query object at 0x8940c2c>

>>> str(Cobbler.objects.filter(id=1).query)
'SELECT `cobblers_cobbler`.`id`, `cobblers_cobbler`.`name`, `cobblers_cobbler`.`description`, `cobblers_cobbler`.`address`, `cobblers_cobbler`.`city`, `cobblers_cobbler`.`post_code`, `cobblers_cobbler`.`telephone`, `cobblers_cobbler`.`email ` FROM `cobblers_cobbler` WHERE `cobblers_cobbler`.`id` = 1  ORDER BY `cobblers_cobbler`.`name` ASC'
>>>