英文:
Django ORM get data by pagination in query level?
问题
我正在使用Django ORM获取员工模型数据,但在该表中有1000-2000个员工数据,现在我只想每次获取一页的数据,对于第2页的原始查询工作方式如下:
SELECT * FROM employee LIMIT 30 OFFSET 60;
其ORM版本如下:
page_number = 3
records_per_page = 30
offset = (page_number - 1) * records_per_page
employees = Employee.objects.all().order_by('id')[offset:offset+records_per_page]
我想知道当数据量很大时是否可以这样使用。因为这里首先获取Employee.objects.all()
,然后进行offset
,它的工作原理是否不同?
英文:
I'm using Django ORM to get Employee modal data, but I have 1000-2000 data of employees in that table, now I want to get only one-page data at a time, for this raw query for 2nd page work like:
SELECT * FROM employee LIMIT 30 OFFSET 60;
and its ORM version is like this:
page_number = 3
records_per_page = 30
offset = (page_number - 1) * records_per_page
employees = Employee.objects.all().order_by('id')[offset:offset+records_per_page]
I want to know if is this correct to use when a large number of data. Because here it gets Employee.objects.all()
and then it offset
records or it's working principle is different way?
答案1
得分: 0
是的,这是正确的,因为Django ORM是惰性的,所以当我们调用Employee.objects.all()时,它只是简单地将查询SELECT * FROM employee
存储在内存中,但不会执行它,直到您决定使用该对象,并且当您设置偏移/限制时,它会将存储在内存中的查询更改为SELECT * FROM employee LIMIT 30 OFFSET 60;
,所以这意味着.all()永远不会运行。
英文:
yes, it is correct because Django ORM is lazy so when we call Employee.objects.all() it simply stores the query SELECT * FROM employee
in the memory but does not execute it until you decide to use the object and when you set the offset/limit it change the query stored in the memory to this SELECT * FROM employee LIMIT 30 OFFSET 60;
so this means that .all() will never run.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论