Roy Tang

Programmer, engineer, scientist, critic, gamer, dreamer, and kid-at-heart.

Blog Notes Photos Links Archives About

Like, have them logged to the console?

Comments

I usually use http://github.com/robhudson/django-debug-toolbar where it tells you the queries and how long they actually take to execute.

Certainly. From the command line/shell:

queryset = Model.objects.filter()
print queryset.query

Variant 2:

from django.db import connection    
queryset = Model.objects.filter()
queryset[0] # This variant needs the queryset to be accessed. Hence.
print connection.queries

If you want to print the queries used to render a page then you can use the toolbar as @Meitham suggested or use this Django snippet.

You can decorate a request handler or other function with this and it will print the sql nicely formated with totals at the end.

from functools import wraps
from django.utils import termcolors
format_ok = termcolors.make_style(opts=('bold',), fg='green')
format_warning = termcolors.make_style(opts=('bold',), fg='yellow')
format_error = termcolors.make_style(opts=('bold',), fg='red')

try:
    from pygments import highlight
    from pygments.lexers import SqlLexer
    from pygments.formatters import TerminalFormatter
    pygments_sql_lexer = SqlLexer()
    pygments_terminal_formatter = TerminalFormatter()
    highlight_sql = lambda s: highlight(s, pygments_sql_lexer,
                               pygments_terminal_formatter)
except ImportError:
    highlight_sql = lambda s: s


def debug_sql(f):
    """
    Turn SQL statement debugging on for a test run.
    """
    @wraps(f)
    def wrapper(*a, **kw):
        from django.conf import settings
        from django.db import connection
        try:
            debug = settings.DEBUG
            settings.DEBUG = True
            connection.queries = []
            return f(*a, **kw)
        finally:
            total_time = 0
            for q in connection.queries:
                fmt = format_ok
                t = float(q['time'])
                total_time += t
                if t > 1:
                    fmt = format_error
                elif t > 0.3:
                    fmt = format_warning
                print '[%s] %s' % (fmt(q['time']), highlight_sql(q['sql']))
            print "total time =", total_time
            print "num queries =", len(connection.queries)
            settings.DEBUG = debug
    return wrapper