python - 在 Django QuerySet 中指定限制和偏移量不起作用

标签 python django django-models django-orm

我正在使用 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/

相关文章:

Python:如何通过 IMAP 将带有 BCC 收件人的电子邮件草稿存储到 Exchange Server?

python - 如何使用 Django 发送/获取 JSON 对象?

django - Django关系

Python 模拟、补丁 os.environ 返回 None

python - 如何将png文件放入字符串并将其写入另一个文件

python - 如何在 cron 作业中将 bash 参数传递给 python 脚本?

python - django 1.8 在另一个 View 中使用一个 View

django - 如何配置 django 表单来销售定制产品?

python - 如何在Django admin中使用ContentTypes的两个应用程序之间的ForeignKey上使用filter_horizo​​ntal?

python - 如何在 Django 中使用 <div class ='field_type'> 标记表单字段