Django - 有没有办法查看ORM正在执行的查询?

时间:2010-09-16 14:16:41

标签: django

喜欢,让他们登录到控制台吗?

3 个答案:

答案 0 :(得分:4)

我通常使用http://github.com/robhudson/django-debug-toolbar 它告诉你查询以及它们实际执行的时间。

答案 1 :(得分:1)

当然可以。从命令行/ shell:

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

变式2:

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

如果要打印用于呈现页面的查询,则可以将工具栏用作@Meitham suggested或使用此Django snippet

答案 2 :(得分:1)

你可以使用它来装饰一个请求处理程序或其他函数,它将在最后打印出与总计很好地形成的sql。

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