获取django在postgresql上运行的所有查询

时间:2010-11-06 22:18:54

标签: django postgresql logging

我正在开发一个django-postgresql项目,我需要查看django在数据库上运行的每个查询(所以我可以微调查询)。有没有办法获得这些查询。 更新:我的开发环境是在ubuntu linux上

4 个答案:

答案 0 :(得分:1)

好吧,你可以设置pgsql服务器来记录每个查询。或者只是记录慢速的。查看postgresql.conf文件,它非常接近自我记录。

答案 1 :(得分:1)

查看此问题(以及最常见的两个答案): django orm, how to view (or log) the executed query?

您还可以查看Djando文档: https://docs.djangoproject.com/en/dev/faq/models/#how-can-i-see-the-raw-sql-queries-django-is-running

希望这有帮助, 安东

答案 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

答案 3 :(得分:0)

试试django debug toolbar。它将显示通过请求执行的所有SQL。当某些事情执行过多的查询时,它变得非常慢。为此,我一直想尝试这个profiler。但是,我已经在几个项目上推出了这个中间件:

try:
    from cStringIO import StringIO
except ImportError:
    import StringIO
from django.conf import settings
from django.db import connection

class DatabaseProfilerMiddleware(object):
    def can(self, request):
        return settings.DEBUG and 'dbprof' in request.GET

    def process_response(self, request, response):
        if self.can(request):
            out = StringIO()
            out.write('time     sql\n')
            total_time = 0
            for query in reversed(sorted(connection.queries, key=lambda x: x['time'])):
                total_time += float(query['time'])*1000
                out.write('%s %s\n' % (query['time'], query['sql']))
            response.content = '<pre style=&quot;white-space:pre-wrap&quot;>%d queries executed in %.3f seconds\n%s</pre>' \
                % (len(connection.queries), total_time/1000, out.getvalue())
        return response

只需转到您感兴趣的请求的相关网址,然后添加dbprof GET参数,您就会看到分析输出而不是正常响应。