ORM debug template tag, http://web-brains.com/2007/12/26/django-orm-query-dumping/

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@register.inclusion_tag('orm_debug.html')
def orm_debug():
import re
try:
from pygments import highlight
from pygments.lexers import SqlLexer
from pygments.formatters import HtmlFormatter
pygments_installed = True
except ImportError:
pygments_installed = False
from django.db import connection
queries = connection.queries
query_time = 0
query_count = 0
if pygments_installed:
formatter = HtmlFormatter()
pygments_css = formatter.get_style_defs()
else:
pygments_css = ''
for query in queries:
query_time += float(query['time'])
query_count += int(1)
query['sql'] = re.sub(r'(FROM|WHERE)', '\n\\1', query['sql'])
query['sql'] = re.sub(r'((?:[^,]+,){3})', '\\1\n ', query['sql'])
if pygments_installed:
query['sql'] = highlight(query['sql'], SqlLexer(), formatter)
return {
'pygments_css': pygments_css,
'pygments_installed': pygments_installed,
'query_time': query_time,
'query_count': query_count,
'queries': queries}