More efficient way of paginating in Django

92 views Asked by At

I am trying to implement pagination in a django project.

I looked at default django paginator and found this example:

def listing(request):
    contact_list = Contacts.objects.all()
    paginator = Paginator(contact_list, 25) # Show 25 contacts per page

    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        contacts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of    results.
        contacts = paginator.page(paginator.num_pages)

    return render_to_response('list.html', {"contacts": contacts})

It looks like it gets ALL the objects from the database and return the needed ones to the template.

That is not very efficient right?

I also looked at django-endless-pagination which seemed really difficult to customize.

I am looking for easily customizable solution as I will integrate it with haystack and elasticsearch

What else can I use?

1

There are 1 answers

0
Animesh Sharma On BEST ANSWER

Paginator won't get all the objects. As in your case, you asked for 25 objects. Thus, each page will contain 25 objects. When you try to access the next page, a new DB request will be sent to access objects 26-50.