If you would like to see the latest queries you have done when running a unittest, this is not so easy. You have to initialize the queries list and set DEBUG to True manually. Then you have to figure out a way to print the queries you want to see just now and format them. I.e., monitoring queries when doing TDD is a bit of a hassle, and this should help.
This little helper does all this for you; your UnitTest only needs to import django.db.connection and store the current length (offset) of the queries list. Then, using Python's coroutine functionality, all you have to do is send that offset to the QueryPrinter coroutine (which you can, for example, initialize as a global variable or a class variable of your UnitTest) and you get the latest SQL printed as a simple table.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | """Debugging queries in django for Django."""
from django.conf import settings
from django.db import connection
def coroutine(func):
def start(*args, **kwargs):
cr = func(*args, **kwargs)
cr.next()
return cr
return start
@coroutine
def QueryPrinter():
"""Initialize a query printer coroutine.
Example use:
>>> query_printer = QueryPrinter()
>>> offset = len(conntection.queries)
>>> # do some stuff that creates SQL queries
>>> query_printer.send(offset)
Now it would print the queries if this example had some. Example Output
looks like:
2 QUERIES AT OFFSET 556
Time/s | SQL
00.006 | 'SELECT ...'
00.006 | 'INSERT INTO ...'
"""
connection.queries = []
settings.DEBUG = True
offset = 0
while True:
diff = len(connection.queries) - offset
if diff:
print diff, "QUERIES AT OFFSET", offset
print "Time/s | SQL"
for query in connection.queries[offset:]:
print "%06.3f | '%s'" % (float(query['time']), query['sql'])
offset = (yield)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.