Django: show/log ORM sql calls from python shell
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 looking for a way to get a log or print-out of all SQL calls generated by the Django ORM in the Python shell. That is, when I do a Django ORM call via the Python shell, I'd like to see the resulting SQL printed out or logged.
I noticed several solutions that add log info to the html page. Is there an easy way to dump to the command line instead?
Solution 1:
If you're using Django 1.3:
import logging
l = logging.getLogger('django.db.backends')
l.setLevel(logging.DEBUG)
l.addHandler(logging.StreamHandler())
Solution 2:
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.
Solution 3:
Rob Hudson's Django Debug Toolbar, as well as its general awesomness, also includes a pretty nifty debugsqlshell
manage.py command which does exactly this.
Solution 4:
Use django extensions.
pip install django-extensions
./manage.py shell_plus --print-sql
For production environments it might not work due to debug settings.