Getting all queries that django run on postgresql

前端 未结 4 351
傲寒
傲寒 2021-01-19 14:31

I am working on a django-postgresql project and I need to see every query that django run on database(so I can fine-tune queries). Is there a way to get those queries. Updat

4条回答
  •  [愿得一人]
    2021-01-19 15:06

    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
    

提交回复
热议问题