Using the excellent Django-Devserver I\'m finding all kinds of interesting and unexpected SQL calls in my code. I wanted to find where the calls are coming from, and so I\'m
Use django extensions.
pip install django-extensions
./manage.py shell_plus --print-sql
For production environments it might not work due to debug settings.
If you're in the shell, or anywhere for that matter, you can use the queryset method
query.as_sql()
to print the SQL command.
ie:
MyModel.objects.all().query.as_sql()
I was trying to use "Django: show/log ORM sql calls from python shell" in a shell on a production server, and it wasn't working. Eventually someone pointed out that it will only do this debug logging when DEBUG = True
. But you can work around that like this:
import logging
from django.db import connection
connection.force_debug_cursor = True # Change to use_debug_cursor in django < 1.8
l = logging.getLogger('django.db.backends')
l.setLevel(logging.DEBUG)
l.addHandler(logging.StreamHandler())
I'm leaving this here so I can find it later, and hopefully it saves someone else the same digging I did.
If you're really serious about wanting to see/log all SQL queries, you'll want to try Django 1.3 (currently in alpha, but soon to be production) which enables Python loggers for many components, including the database backends.
Of course, if you're stuck using a stable version of Django, you can get the same effect relatively easily by patching django/db/models/sql/compiler.py
by adding this to the bottom of the import list:
import logging
_querylogger = logging.getLogger( 'sql.compiler' )
The find the SQLCompiler::execute_sql()
method and change:
cursor = self.connection.cursor()
cursor.execute( sql, params )
to this:
cursor = self.connection.cursor()
_querylogger.info( "%s <= %s", sql, params )
cursor.execute( sql, params )
qs = YourModel.objects.all()
qs.query.get_compiler('default').as_sql()
If you're using Django 1.3:
import logging
l = logging.getLogger('django.db.backends')
l.setLevel(logging.DEBUG)
l.addHandler(logging.StreamHandler())