Tuesday, November 20, 2012

Debugging SQL in Django (with PyDev)

I'm working on a Django project recently and one of the things that came up was debugging SQL statements a bit to see what was actually going on.

After researching a bit, I found: http://pypi.python.org/pypi/django-debug-toolbar, which when installed wraps around the calls that Django does to the DB and prints the actual SQL statements used.

I didn't really install it as a debug toolbar as it recommends, but I use it in the interactive console shell to see how things happen when I'm experimenting.

To do this, after installing it and adding 'debug_toolbar' to your INSTALLED_APPS in Django, one can start the interactive console shell with Django support (if you're in a Python editor just do: Ctrl+2 dj shell) and add write the import:

from debug_toolbar.management.commands import debugsqlshell

Now, when you do some operation that does an SQL operation, it'll be printed to the console, while having all the PyDev niceties on the console (such as code-completion). Pretty nice.