SCo*_*vin 4 sql django performance django-models backtrace
我希望在请求期间执行的每个查询都有回溯,因此我可以找到它们的来源并减少计数/复杂性.
我正在使用这个优秀的中间件片段来列出和查询时间,但我不知道它们来自哪里.
我在django/db/models/sql/compiler.py中搜索过,但是明显的形式是获取本地版本的django并编辑该代码我无法看到如何锁定查询.有没有可以使用的信号?似乎每个查询都没有信号.
是否可以指定默认值Manager?
(我知道django-toolbar,我希望有一个解决方案,而不使用它.)
一个丑陋但有效的解决方案(例如,它在所有查询上打印跟踪,只需要一次编辑)是将以下内容添加到底部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
Run Code Online (Sandbox Code Playgroud)
仍然不确定是否有更优雅的方式这样做?