tags:

views:

1524

answers:

4

is there a way to show the sql that django is running while performing a query?

ANSWER: import connection from django.db

from django.db import connection
print connection.queries
[{'sql': 'SELECT polls_polls.id,polls_polls.question,polls_polls.pub_date FROM polls_polls'; 'time': '0.002'}]
+5  A: 

Try the docs FAQ: How can I see the raw SQL queries Django is running?

geowa4
To future proof this answer you should rather link the current version of Django's documentation: http://docs.djangoproject.com/en/dev/faq/models/#how-can-i-see-the-raw-sql-queries-django-is-running
Andre Miller
+2  A: 

Though you can do it with with the code supplied, I find that using the debug toolbar app is a great tool to show queries. You can download it from github here.

This gives you the option to show all the queries ran on a given page along with the time to query took. It also sums up the number of queries on a page along with total time for a quick review. This is a great tool, when you want to look at what the Django ORM does behind the scenes. It also have a lot of other nice features, that you can use if you like.

googletorp
A: 

Take a look at debug_toolbar, it's very usefull for debugging.

Glader
+1  A: 

If you make sure your settings.py file has:

  1. django.core.context_processors.debug listed in CONTEXT_PROCESSORS
  2. DEBUG=True
  3. your IP in the INTERNAL_IPS tuple

Then you should have access to the sql_queries variable. I append a footer to each page that looks like this:

    {%if sql_queries %}<div class="footNav">
  <h2>Queries</h2>
  <p>
    {{ sql_queries|length }} Quer{{ sql_queries|pluralize:"y,ies" }}, {{sql_time_sum}} Time
    {% ifnotequal sql_queries|length 0 %}
    (<span style="cursor: pointer;" onclick="var s=document.getElementById('debugQueryTable').style;s.disp\
lay=s.display=='none'?'':'none';this.innerHTML=this.innerHTML=='Show'?'Hide':'Show';">Show</span>)
    {% endifnotequal %}
  </p>
  <table id="debugQueryTable" style="display: none;">
    <col width="1"></col>
    <col></col>
    <col width="1"></col>
    <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">SQL</th>
      <th scope="col">Time</th>
    </tr>
    </thead>
    <tbody>
    {% for query in sql_queries %}<tr class="{% cycle odd,even %}">
      <td>{{ forloop.counter }}</td>
      <td>{{ query.sql|escape }}</td>
      <td>{{ query.time }}</td>
    </tr>{% endfor %}
    </tbody>
  </table>

</div>{%endif %}

I got the variable sql_time_sum by adding the line

context_extras['sql_time_sum'] = sum([float(q['time']) for q in connection.queries])

to the debug function in django_src/django/core/context_processors.py.

Mike Howsden