Skip to content

Instantly share code, notes, and snippets.

@robhudson
Created May 28, 2009 00:02
Show Gist options
  • Save robhudson/118990 to your computer and use it in GitHub Desktop.
Save robhudson/118990 to your computer and use it in GitHub Desktop.
Copy/Paste to print SQL in the Django shell
"""
A quick copy/paste action you can drop into your `./manage.py shell` session so any
queries executed are displayed in the shell output.
If sqlparse is available it will use that to pretty print the SQL:
http://code.google.com/p/python-sqlparse/
"""
from django.db.backends import util
try:
import sqlparse
except ImportError:
sqlparse = None
class PrintQueryWrapper(util.CursorDebugWrapper):
def execute(self, sql, params=()):
try:
return self.cursor.execute(sql, params)
finally:
raw_sql = self.db.ops.last_executed_query(self.cursor, sql, params)
if sqlparse:
print sqlparse.format(raw_sql, reindent=True)
else:
print raw_sql
print
util.CursorDebugWrapper = PrintQueryWrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment