在Django QuerySet won中指定限制和偏移

2024-04-19 12:26:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是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。

为什么?有什么我需要配置的吗?


Tags: djangofromimportsqllenobjectsmodelsmysql
3条回答

我为自己使用和工作的补偿和限制:)

MyModel.objects.all()[offset:limit]

例如:

Post.objects.filter(Post_type=typeId)[1:1]

Django使用Python的数组切片语法实现OFFSET。如果要偏移前10个元素,然后显示下5个元素,请使用它

MyModel.objects.all()[OFFSET:OFFSET+LIMIT]

例如,如果希望在偏移量为10后检查5个作者,则代码将如下所示:

Author.objects.all()[10:15]

你可以阅读更多关于它的内容here in the official Django doc

当您从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

相关问题 更多 >