Arbazz Hussain
Arbazz Hussain

Reputation: 1932

Pagination Concept in Django & efficient way to implement over large objects

While learning Django Concepts, I Came across the pagination concept at: https://docs.djangoproject.com/en/2.2/topics/pagination/

I understand that pagination is used for rendering the object fields of the model into discrete pages.

In the documentation, the Author provided the following snippet that :

contact_list = Contacts.objects.all() paginator = Paginator(contact_list, 25)

Which is basically loading all objects of model Contacts and putting them into pagination to limit the per page size to 25.

My Question here is: Imagine we have thousands of objects under Contacts model with large TextField, doing Contacts.objects.all() will take some time, In this situation what would be the best efficient way to implement pagination such that pagination happens over Contacts.objects instead of loading all and then passing to Paginator.

Upvotes: 2

Views: 571

Answers (1)

heemayl
heemayl

Reputation: 41987

Django Paginator (django.core.paginator.Paginator) class uses a slice on queryset, which is run as a LIMIT query on database, so it does not get all the instances and then get the subset, rather it only retrieves the subset from databse using LIMIT. In case of offset, it uses LIMIT <> OFFSET <>, so that's efficient as well.

Django querysets are lazy, so when you do Contacts.objects.all() and pass it to the paginator, it is not evaluated then -- it will be evaluated later when the paginator actually tries to slice it to get the required number of elements for a given page.

Upvotes: 4

Related Questions