Задать вопрос

Тел: +7 965 3737 888

521

Просмотров

1

Ответов

Yet another SQL debugging facility

<p>Inspired by http://www.djangosnippets.org/snippets/159/</p>
<p>This context processor provides a new variable {{ sqldebug }}, which can 
be used as follows:</p>
<p>{% if sqldebug %}...{% endif %}
{% if sqldebug.enabled %}...{% endif %}</p>
This checks settings.SQL_DEBUG and settings.DEBUG. Both need to be True,
otherwise the above will evaluate to False and sql debugging is considered
to be disabled.

<p>{{ sqldebug }}</p>
This prints basic information like total number of queries and total time.

<p>{{ sqldebug.time }}, {{ sqldebug.queries.count }}</p>
Both pieces of data can be accessed manually as well.

<p>{{ sqldebug.queries }}</p>
Lists all queries as LI elements.

<p>{% for q in sqldebug.queries %}  <br>
    &lt;li&gt;{{ q.time }}: {{ q }}&lt;/li&gt;
{% endfor %}</p>
Queries can be iterated as well. The query is automatically escaped and contains
&lt;wbr&gt; tags to improve display of long queries. You can use {{ q.sql }} to access
the unmodified, raw query string.

<p>Here's a more complex example. It the snippet from:
    http://www.djangosnippets.org/snippets/93/
adjusted for this context processor.</p>
{% if sqldebug %}
&lt;div id="debug"&gt;
  &lt;p&gt;
    {{ sqldebug.queries.count }} Quer{{ sqldebug.queries|pluralize:"y,ies" }}, {{ sqldebug.time }} seconds
    {% ifnotequal sql_queries|length 0 %}
    (&lt;span style="cursor: pointer;" onclick="var s=document.getElementById('debugQueryTable').style;s.display=s.display=='none'?'':'none';this.innerHTML=this.innerHTML=='Show'?'Hide':'Show';"&gt;Show&lt;/span&gt;)
    {% endifnotequal %}
  &lt;/p&gt;
  &lt;table id="debugQueryTable" style="display: none;"&gt;
    &lt;col width="1"&gt;&lt;/col&gt;
    &lt;col&gt;&lt;/col&gt;
    &lt;col width="1"&gt;&lt;/col&gt;
    &lt;thead&gt;
    &lt;tr&gt;
      &lt;th scope="col"&gt;#&lt;/th&gt;
      &lt;th scope="col"&gt;SQL&lt;/th&gt;
      &lt;th scope="col"&gt;Time&lt;/th&gt;
    &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
    {% for query in sqldebug.queries %}&lt;tr class="{% cycle odd,even %}"&gt;
      &lt;td&gt;{{ forloop.counter }}&lt;/td&gt;
      &lt;td&gt;{{ query }}&lt;/td&gt;
      &lt;td&gt;{{ query.time }}&lt;/td&gt;
    &lt;/tr&gt;{% endfor %}
    &lt;/tbody&gt;
  &lt;/table&gt;
&lt;/div&gt;
{% endif %}

Вопрос полезен? Да0/Нет0
file_2641.py(2.2Кб)
None

Ответы (1):

Ответtechiegurl:05.05.2008
Ответ полезен? Да0/Нет0

I love the idea that this is as simple as adding a new variable to the templates. Please forgive the newbie question though. To use this snippet, is adding it as a custom templatetag file enough?

Thank you in advance :)