简体   繁体   English

切片Django查询集而无需从数据库中检索所有内容

[英]Slicing a Django queryset without retrieving everything from the database

Lets say, I want the first 12 elements from a Django queryset. 可以说,我想要Django queryset中的前12个元素。 Now I could easily do this as follows: 现在,我可以轻松地按以下步骤进行操作:

queryset = Content.objects.all()[:12]

This works, but I am retrieving every single Content from my database. 这可行,但是我正在从数据库中检索每个单个Content。 Is there a better way to do this? 有一个更好的方法吗? I am thinking something that only retrieves the first 12 items from the queryset from the database. 我在想什么只能从数据库的查询集中检索前12个项目。

Thanks. 谢谢。

Actually, that is the correct limit syntax for the django ORM. 实际上,这是django ORM的正确限制语法。 If you open up a shell and try it out you will notice what it is doing. 如果打开外壳并尝试使用它,您会注意到它在做什么。

>>> queryset = Content.objects.all()[:12]
>>> queryset
<QuerySet [...]>
>>> str(queryset.query)
'SELECT * FROM "content" LIMIT 12'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM