Django lazy QuerySet and pagination

白昼怎懂夜的黑 提交于 2019-11-27 11:43:01

If you want to see where are occurring, import django.db.connection and inspect queries

>>> from django.db import connection
>>> from django.core.paginator import Paginator
>>> queryset = Entry.objects.all()

Lets create the paginator, and see if any queries occur:

>>> paginator = Paginator(queryset, 10)
>>> print connection.queries 
[]

None yet.

>>> page = paginator.page(4)
>>> page
<Page 4 of 788>
>>> print connection.queries 
[{'time': '0.014', 'sql': 'SELECT COUNT(*) FROM `entry`'}]

Creating the page has produced one query, to count how many entries are in the queryset. The entries have not been fetched yet.

Assign the page's objects to the variable 'objects':

>>> objects = page.object_list
>>> print connection.queries
[{'time': '0.014', 'sql': 'SELECT COUNT(*) FROM `entry`'}]

This still hasn't caused the entries to be fetched.

Generate the HttpResponse from the object list

>>> response = HttpResponse(page.object_list)
>>> print connection.queries
[{'time': '0.014', 'sql': 'SELECT COUNT(*) FROM `entry`'}, {'time': '0.011', 'sql': 'SELECT `entry`.`id`, <snip> FROM `entry` LIMIT 10 OFFSET 30'}]

Finally, the entries have been fetched.

It is. Django's pagination uses the same rules/optimizations that apply to querysets.

This means it will start evaluating on return HttpResponse(output)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!