要在自带的runserver 下运行,也就是开发环境下,为了方便部署,在 project 目录新建一个文件:
debug.py
再建一个中间件在project目录下:
sqlmiddleware.py
准备工作做完了。下面运行服务器吧:
python manage.py runserver 127.0.0.1:8000 --settings debug
好了,你的每一次request都会在shell中看到SQL语句了。
debug.py
#coding=utf8
DEBUG=True
MIDDLEWARE_CLASSES += ('sqlmiddleware.PrintSQL',)
再建一个中间件在project目录下:
sqlmiddleware.py
#coding=utf8
from django.db import connection
class PrintSQL(object):
def process_response(self, request, response):
temp = 0
for x in connection.queries:
print x
temp += float(x['time'])
print 'time count:',temp,'=' * 40准备工作做完了。下面运行服务器吧:
python manage.py runserver 127.0.0.1:8000 --settings debug
好了,你的每一次request都会在shell中看到SQL语句了。
本文介绍了一种在Django项目中调试SQL查询的方法。通过在项目目录下创建debug.py和sqlmiddleware.py两个文件,可以实现在开发环境中查看每次请求产生的SQL语句及其执行时间。

被折叠的 条评论
为什么被折叠?



