Created
May 28, 2009 00:02
-
-
Save robhudson/118990 to your computer and use it in GitHub Desktop.
Copy/Paste to print SQL in the Django shell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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 | |
util.CursorDebugWrapper = PrintQueryWrapper | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment