开发者

Getting Django Query Count While in manage.py shell

开发者 https://www.devze.com 2022-12-18 00:39 出处:网络
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.

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/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号