Django打印请求的sql

我们平时都是用django的ORM来进行数据库操作,ORM会将我们的Python代码转换成sql语句。但是,有的时候我们得到的结果并不是理想中的结果,这时候一个有效的debug方法就是查看ORM生成的sql语句。下面是获取sql的方法:

>>> from django.db import connection
>>> connection.queries
[{'sql': 'SELECT polls_polls.id, polls_polls.question, polls_polls.pub_date FROM polls_polls',
'time': '0.002'}]

注意: 只有在DEBUG=True的情况下才能获取sql,不然拿到的是一个空list

Limit 21

我们拿到sql的时候经常会看到最后有一个limit 21,但是我们的代码里并没有给查询做限制,这个limit是哪里来的呢?下面是从django的邮件列表里找到的回答:

It happens when you make queries from the shell - the LIMIT clause is added to stop your terminal filling up with thousands of records when debugging:

You were printing (or, at least, trying to print) the repr() of the queryset. To avoid people accidentally trying to retrieve and print a million results, we (well, I) changed that to only retrieve and print the first 20 results and print “remainder truncated” if there were more. This is achieved by limiting the query to 21 results (if there are 21 results there are more than 20, so we print the “truncated” message). That only happens in the repr() – i.e. it’s only for diagnostic printing. No normal user code has this limit included automatically, so you happily create a queryset that iterates over a million results.

简而言之,你的这个查询预期会返回很多行记录,但是为了在打印的时候不让屏幕充满这些数据(这些数据根本看不出来东西,垃圾数据),所以django在这些语句后面加了limit 21

参考

http://stackoverflow.com/questions/24041448/specifying-limit-and-offset-in-django-queryset-wont-work

http://www.mail-archive.com/django-users@googlegroups.com/msg67486.html

https://docs.djangoproject.com/en/1.9/faq/models/