I extended the Django CursorDebugWrapper execute routine so on the server side I can keep track of all SQL executed. Looks like this:
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
The problem is that I need each user session to do this individually, otherwise it will record all sql from all users with no concept of what came from where. If I can access the user ID from execute() I can easily keep track of the SQL from each user, but I don’t know how to do that without having access to the request object.
Note: I cannot claim credit for the above code. It originated from the Django Debug Toolbar.
You can make it with middleware:
middleware.py:
settings.py: