本文实例讲述了获取django框架orm query执行的sql语句实现方法。分享给大家供大家参考,具体如下:
利用django orm 可以很方便的写出很多查询,但有时候,我们需要检查这些利用 orm 生成的 sql 语句是否正确,就需要检查这些orm 生成的 原生的sql 语句是否正确。经过测试有如下几种方法:
1. 通过数据库的跟踪日志,可以看到查询的语句,比如mysql 就可以配置把所有的 sql 语句打印到日志中,但这种方式并不推荐,只是没有办法的时候才这么做。
2. 利用django query 提供的方法. 比如:
1
2
3
|
queryset = mymodel.objects. all () print 'query sql: ' + str (queryset .query) #result: |
我采用pydev 对 django 进行debug, 如下是截图,可以清楚的看到结果:
3. 设置settings 里的 debug=true
, 这个时候可以用这种方式来获取
1
2
|
from django.db import connections connections[ 'default' ].queries |
结果类似如下:
[{u'time': u'0.000', u'sql': u'select count(*) from `my_article` where `my_article`.`category` = 68 '}]
4. 利用三方提供的middleware 来实现,参考这里: https://djangosnippets.org/snippets/290/
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
45
46
|
from django.db import connection from django.conf import settings import os def terminal_width(): """ function to compute the terminal width. warning: this is not my code, but i've been using it forever and i don't remember where it came from. """ width = 0 try : import struct, fcntl, termios s = struct.pack( 'hhhh' , 0 , 0 , 0 , 0 ) x = fcntl.ioctl( 1 , termios.tiocgwinsz, s) width = struct.unpack( 'hhhh' , x)[ 1 ] except : pass if width < = 0 : try : width = int (os.environ[ 'columns' ]) except : pass if width < = 0 : width = 80 return width class sqlprintingmiddleware( object ): """ middleware which prints out a list of all sql queries done for each view that is processed. this is only useful for debugging. """ def process_response( self , request, response): indentation = 2 if len (connection.queries) > 0 and settings.debug: width = terminal_width() total_time = 0.0 for query in connection.queries: nice_sql = query[ 'sql' ].replace( '"' , ' ').replace(' , ',' , ') sql = "\033[1;31m[%s]\033[0m %s" % (query[ 'time' ], nice_sql) total_time = total_time + float (query[ 'time' ]) while len (sql) > width - indentation: print "%s%s" % ( " " * indentation, sql[:width - indentation]) sql = sql[width - indentation:] print "%s%s\n" % ( " " * indentation, sql) replace_tuple = ( " " * indentation, str (total_time)) print "%s\033[1;32m[total time: %s seconds]\033[0m" % replace_tuple return response |
当然,定义了这个middleware之后,需要修改setting 里的配置
1
2
3
4
5
6
7
8
9
10
|
middleware_classes = ( 'django.middleware.common.commonmiddleware' , 'django.contrib.sessions.middleware.sessionmiddleware' , 'django.middleware.csrf.csrfviewmiddleware' , 'django.contrib.auth.middleware.authenticationmiddleware' , 'django.contrib.messages.middleware.messagemiddleware' , 'yihaomen.common.mymiddleware.sqlprintingmiddleware' , # 这是增加的显示sql语句的middleware # uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.xframeoptionsmiddleware', ) |
结果会打印所有执行的sql 语句, 推荐采用这种方式打印 sql 语句,因为比较方便,而且是插拔式的,不需要的时候去掉这个middleware就可以了,不过这只能在debug 模式下使用,对开发者来说足够了,生产环境不需要debug模式。
希望本文所述对大家基于django框架的python程序设计有所帮助。
原文链接:http://www.yihaomen.com/article/python/448.htm