Skip to content

Instantly share code, notes, and snippets.

@wil
Created January 3, 2012 10:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wil/1554441 to your computer and use it in GitHub Desktop.
Save wil/1554441 to your computer and use it in GitHub Desktop.
Django Production SQL Debugging in the manage.py shell
# These are some commands to copy and paste into a manage.py shell session
# in order to find out what SQL queries are generated by a view
## turn on DEBUG so that ``connection.queries`` gets populated
from django.conf import settings
settings.DEBUG = True
from django.db import connection
## handy function for printing the queries
def print_q(queries, sort=None, truncate=100):
if sort is not None:
queries = sorted(queries, key=lambda x: float(x['time']), reverse=not sort)
for q in queries:
print q['time'], q['sql'][:truncate]
print_q(connection.queries, True)
## call the view!
from django.test.client import Client
c = Client()
url = '/my/url'
c.get(url)
print_q(connection.queries, True)
sum(map(lambda x: float(x['time']), connection.queries))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment