Is there a way to count my queries during a manage.py shell session? It would be helpful as a means to inspect some of the ORM behavior between queries.
Additionally, it would be nice to pull the queries themselves, and I guess the开发者_如何学Pythonir execution times while I'm at it.
i.e.
>>>from myapp.models import User
>>>User.objects.filter(name='Bob')
>>>User.objects.filter(name='Bob')
>>>[wth is my query count]
>>>User.objects.all()
>>>[wth is my query count]
>>>User.objects.filter(name='Greg')
>>>[wth is my query count]
QuerySet
objects have a .count()
method, and can also be given to len()
if that's what you're looking for:
>>> User.objects.filter(name='Bob')
>>> _.count()
You can also inspect the queries using ._as_sql()
>>> User.objects.filter(name='Bob')._as_sql()
or get all the queries already made (with their execution times) with
>>> from django.db import connection
>>> connection.queries
Note that just calling User.objects.filter(name='Bob')
wont actually exceute any SQL queries. Django waits until you do something with it before it executes the SQL query.
You can make the queries more readable by installing the python module sqlparse
and doing something like this:
>>> import sqlparse
>>> def sql(qs):
... return sqlparse.format(qs._as_sql()[0], reindent=True, keyword_case='upper')
>>> print sql(User.objects.filter(name='Bob'))
See http://code.google.com/p/python-sqlparse/
精彩评论