As part of the Django’s common Web application tools, Django offers a few classes to manage paginated data. You can
pass either a list/tuple of objects or an QuerySet. In this tutorial I will show how to paginate data using function
based views and how to paginate using class-based views (ListView).
The Paginator
The paginator classes lives in django.core.paginator. We will be working mostly with the Paginator and Page
classes.
Consider the auth.User table has 53 user instances.
In the example above I’m telling Paginator to paginate the user_listQuerySet in pages of 10. This will create
a 6 pages result. The first 5 pages with 10 users each and the last page with 3 users.
Debugging the Paginator Object
Input
Output
Type
paginator.count
53
<type 'int'>
paginator.num_pages
6
<type 'int'>
paginator.page_range
xrange(1, 7)
<type 'xrange'>
paginator.page(2)
<Page 2 of 6>
<class 'django.core.paginator.Page'>
The Paginator.page() method will return a given page of the paginated results, which is an instance of Page. This
is what we will return to the template.
Debugging the Page Object
Input
Output
Type
users
<Page 2 of 6>
<class 'django.core.paginator.Page'>
users.has_next()
True
<type 'bool'>
users.has_previous()
True
<type 'bool'>
users.has_other_pages()
True
<type 'bool'>
users.next_page_number()
3
<type 'int'>
users.previous_page_number()
1
<type 'int'>
users.start_index()
11
<type 'int'>
users.end_index()
20
<type 'int'>
The Page.next_page_number() and Page.previous_page_number() methods raises InvalidPage if next/previous page
doesn’t exist.
The Page.start_index() and Page.end_index() are relative to the page number.
The process is basically done by querying the database, then pass the QuerySet to the Paginator, grab a Page and return
to the template. The rest is done in the template.