Django查询追溯 [英] Django traceback on queries

查看:182
本文介绍了Django查询追溯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望对请求期间执行的每个查询进行追溯,因此我可以找到它们的来源并减少计数/复杂性。

I want a traceback from every query executed during a request, so I can find where they're coming from and reduce the count/complexity.

我使用很好的中间件代码片段来列出和查询时间,但是我不知道他们来自。

I'm using this excellent snippet of middleware to list and time queries, but I don't know where in the they're coming from.

我在 django / db / models / sql / compiler.py 但明显的形式是获取django的本地版本并编辑该代码,我看不到如何锁定查询。我可以使用一个信号吗?似乎没有并不是每个查询都发出信号

I've poked around in django/db/models/sql/compiler.py but apparent form getting a local version of django and editing that code I can't see how to latch on to queries. Is there a signal I can use? it seems like there isn't a signal on every query.

是否可以指定默认的 Manager

(我知道django-工具栏,我希望有一个不用的解决方案。)

(I know about django-toolbar, I'm hoping there's a solution without using it.)

推荐答案

一个丑陋但有效的解决方案(例如,它打印出跟踪所有查询,只需要进行一次编辑即可)将以下内容添加到 settings.py 的底部:

An ugly but effective solution (eg. it prints the trace on all queries and only requires one edit) is to add the following to the bottom of settings.py:

import django.db.backends.utils as bakutils
import traceback

bakutils.CursorDebugWrapper_orig = bakutils.CursorWrapper

def print_stack_in_project():
    stack = traceback.extract_stack()
    for path, lineno, func, line in stack:
        if 'lib/python' in path or 'settings.py' in path:
            continue
        print 'File "%s", line %d, in %s' % (path, lineno, func)
        print '  %s' % line

class CursorDebugWrapperLoud(bakutils.CursorDebugWrapper_orig):
    def execute(self, sql, params=None):
        try:
            return super(CursorDebugWrapperLoud, self).execute(sql, params)
        finally:
            print_stack_in_project()
            print sql
            print '\n\n\n'

    def executemany(self, sql, param_list):
        try:
            return super(CursorDebugWrapperLoud, self).executemany(sql, param_list)
        finally:
            print_stack_in_project()
            print sql
            print '\n\n\n'

bakutils.CursorDebugWrapper = CursorDebugWrapperLoud

仍然不确定是否有更优雅的方法吗?

Still not sure if there is a more elegant way of doing this?

这篇关于Django查询追溯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆