Django ORM如何在查询级别通过分页获取数据?

huangapple go评论78阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月1日 15:32:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76379616.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定