我扩展了Django CursorDebugWrapper执行例程,所以在服务器端我可以跟踪所有执行的SQL。看起来像这样:
class PrintQueryWrapper(django.db.backends.util.CursorDebugWrapper):
def execute(self, sql, params=()):
try:
return self.cursor.execute(sql, params)
finally:
# record sql and do other stuff
django.db.backends.util.CursorDebugWrapper = PrintQueryWrapper
问题是我需要每个用户会话单独执行此操作,否则它将记录来自所有用户的所有sql,而不知道来自哪里的概念。如果我可以从execute()访问用户ID,我可以轻松跟踪每个用户的SQL,但我不知道如何在不访问请求对象的情况下执行此操作。
注意:我无法声明上述代码。它起源于Django调试工具栏。
答案 0 :(得分:1)
您可以使用中间件:
middleware.py:
import django.db.backends.util
class PrintQueryWrapper(django.db.backends.util.CursorDebugWrapper):
user_id = None
def execute(self, sql, params=()):
try:
return self.cursor.execute(sql, params)
finally:
print self.user_id, ": ", sql
class PrintQueryMiddleware(object):
def process_request(self, request):
PrintQueryWrapper.user_id = request.user.pk
django.db.backends.util.CursorDebugWrapper = PrintQueryWrapper
settings.py:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'main.middleware.PrintQueryMiddleware', # chnage path to your app
)