有没有办法记录在Django视图中进行的查询的总数?
问题描述:
我有非传统的视图,响应ajax请求。通常,我使用调试工具栏来获取查询计数,但是,由于此特定视图只是返回一些json,因此没有用于显示自身的调试工具栏的页面。有没有办法记录在Django视图中进行的查询的总数?
有没有办法将在视图中执行的查询总数打印出来给控制台?
从浏览文档,找到qs.query
。然而,这只是给我的基地orm查找。我真的在寻找从我看来发生的所有事情的总和(例如,通过遍历外键触发的附加查询)。
答
你可以写一个中间件用于此目的:
from django.db import connection
class SqlPrintMiddleware(object):
def process_response(self, request, response):
sqltime = 0 # Variable to store execution time
for query in connection.queries:
sqltime += float(query["time"]) # Add the time that the query took to the total
# len(connection.queries) = total number of queries
print "Page render: " + unicode(sqltime) + "sec for " + unicode(len(connection.queries)) + " queries"
return response
而在你的settings.py变化:
MIDDLEWARE_CLASSES = (
# ...
'your_app.middleware.SqlPrintMiddleware',
# ...
)
理念采取从here