msgbartop
by Brian Neal
msgbarbottom

25 Jan 09 Displaying a Page’s SQL Queries

I’ve been meaning to start paying attention to the SQL queries that Django is generating for me. I’d like to know if there are any dumb things I am doing. And down the road I am going to start employing low-level caching, and seeing what queries I am doing will help me decide what things to cache. I finally broke down and figured out how you can display the SQL queries used during an HTTP request on the rendered web page. Django makes this quite easy and it is fully documented.

If your TEMPLATE_CONTEXT_PROCESSORS in your settings.py file contains “django.core.context_processors.debug”, and DEBUG is set to True, you have access to a variable in your templates called sql_queries. This is an ordered list of {'sql': ..., 'time': ...} dictionaries that represent every SQL query and how long each one took during the processing of the request.

It was quite easy to add the following to the very bottom of my site’s base template:

{% if debug %}
<div id="debug">
<ol>
{% for s in sql_queries %}
<li>{{ s.sql }} : <b>({{ s.time }})</b></li>
{% endfor %}
</ol>
</div>
{% endif %}

Now I can keep an eye on what’s happening at the database level. I’ve already added a few key “select_related” clauses to some of my Django ORM queries that have saved 10-30% on the number of trips to the database per page. Cool!

Tags: , ,