我正在使用 Django 1.6.5 并打开了 MySQL 的一般查询日志,因此我可以看到 sql 命中 MySQL。
我注意到在 Django 的 QuerySet 中指定更大的限制是行不通的:
>>> from blog.models import Author
>>> len(Author.objects.filter(pk__gt=0)[0:999])
>>> len(Author.objects.all()[0:999])
MySQL 的一般日志显示这两个查询都有 LIMIT 21
。
但是小于 21 的限制是可行的,例如len(Author.objects.all()[0:10])
将使用 LIMIT 10
生成一个 sql。
这是为什么呢?有什么我需要配置的吗?
最佳答案
当您从 shell 进行查询时会发生这种情况 - 添加了 LIMIT
子句以阻止您的终端在调试时填满数千条记录:
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.
( Source )
关于python - 在 Django QuerySet 中指定限制和偏移量不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24041448/