简体   繁体   English

Django分页。 如果我有一百万行怎么办?

[英]Django pagination. What if I have 1 million of rows?

The official Django Documentation gives us something like this: 官方Django文档为我们提供了以下内容:

from django.core.paginator import Paginator
my_list = MyModel.objects.all()
p = Paginator(my_list, 10)

But. 但。 What if I have to paginate 1 million of rows? 如果我必须对100万行进行分页怎么办? It's not so efficient to load the 1 million rows with MyModel.objects.all() every time I want to view a single paginated page. 每次我要查看单个分页页面时,使用MyModel.objects.all()加载一百万行并不是那么有效。

Is there a more efficient way to do this without the need of call objects.all() to make a simple pagination? 有没有更有效的方法可以做到这一点而无需调用objects.all()进行简单的分页?

MyModel.objects.all() doesn't actually load all of the objects. MyModel.objects.all()实际上不会加载所有对象。 It could potentially load all of them, but until you actually perform an action that requires it to be evaluated, it won't do anything. 它可能会全部加载它们,但是直到您实际执行要求对其进行评估的操作之前,它什么也不会做。

The Paginator will almost certainly add some limits on that query set. 分页器几乎肯定会对该查询集增加一些限制。 For example, using array-slicing notation, it can create a new object, like this 例如,使用数组切片表示法,它可以创建一个新的对象,如下所示

my_list = MyModel.objects.all()
smaller_list = my_list[100:200]

That will create a different query set, which will only request 100 items from the database. 这将创建一个不同的查询集,该查询集将仅从数据库中请求100个项目。 Or calling .count() on the original query set, which will just instruct the database to return the number of rows in the table. 或在原始查询集上调用.count() ,这只会指示数据库返回表中的行数。

You would have to do something that requires all of the objects to be retrieved, like calling 您将需要执行一些需要检索所有对象的操作,例如调用

list(my_list)

to get 1000000 rows to be transferred from the database to Python. 得到1000000行要从数据库传输到Python。

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

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