paging
Django provides classes to help you manage paged data — that is, data is divided into different pages with a “previous / next” tag. These classes are located indjango/core/paginator.py
In the middle.
Examples
towardsPaginator
Provide a list of objects and the number of elements you want to assign to each page. It will provide you with a way to access the objects on each page
>>> from django.core.paginator import Paginator
>>> objects = ['john', 'paul', 'george', 'ringo']
>>> p = Paginator(objects, 2)
>>> p.count
4
>>> p.num_pages
2
>>> p.page_range
[1, 2]
>>> page1 = p.page(1)
>>> page1
<Page 1 of 2>
>>> page1.object_list
['john', 'paul']
>>> page2 = p.page(2)
>>> page2.object_list
['george', 'ringo']
>>> page2.has_next()
False
>>> page2.has_previous()
True
>>> page2.has_other_pages()
True
>>> page2.next_page_number()
Traceback (most recent call last):
...
EmptyPage: That page contains no results
>>> page2.previous_page_number()
1
>>> page2.start_index() # The 1-based index of the first item on this page
3
>>> page2.end_index() # The 1-based index of the last item on this page
4
>>> p.page(0)
Traceback (most recent call last):
...
EmptyPage: That page number is less than 1
>>> p.page(3)
Traceback (most recent call last):
...
EmptyPage: That page contains no results
be careful
Note that you can askPaginator
Provide a list or tuple, Django’sQuerySet
Or anything withcount()
or__len__()
Method. When calculating the number of objects contained in an incoming object,Paginator
Will try to call thecount()
, and then if the incoming object does notcount()
Methodlen()
. This will make Django likeQuerySet
Using more efficientcount()
Methods, if they exist.
usePaginator
Here are a few more complex examples that are used in the viewPaginator
To page the query set. We provide views and related templates to show how to present these results. This example assumes that you have an importedContacts
Model.
The view function looks like this:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
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})
staylist.html
In the template, you want to include navigation between pages, as well as any interesting information from the object itself:
<div class="pagination">
<span class="step-links">
<span class="current">
Page of .
</span>
</span>
</div>
Paginator objects
Paginator
Class has the following constructors:
_class _Paginator
(_object_list_, _per_page_, _orphans=0_, _allow_empty_first_page=True_)[source]
Required parameters
object_list
A list, tuple, Django QuerySet
, or other sliceable object with acount()
or __len__()
method.
per_page
The maximum number of items to include on a page, not including orphans
(see the orphans
optional argument below).
Optional parameters
orphans
The minimum number of items allowed on the last page, defaults to zero.
Use this when you don’t want to have a last page with very few items.
If the last page would normally have a number of items less than or equal
to orphans
, then those items will be added to the previous page (which
becomes the last page) instead of leaving the items on a page by
themselves. For example, with 23 items, per_page=10
, andorphans=3
, there will be two pages; the first page with 10 items and
the second (and last) page with 13 items.
allow_empty_first_page
Whether or not the first page is allowed to be empty. If False
andobject_list
is empty, then an EmptyPage
error will be raised.
method
Paginator.
`page`(_number_)[source]
Returns the value at the provided subscriptPage
Object, subscript starts with 1. If the page number provided does not exist, theInvalidPage
Abnormal.
attribute
Paginator.
`count`
The total number of objects for all pages.
be careful
When calculatingobject_list
The number of objects contained,Paginator
Will try to call theobject_list.count()
. Ifobject_list
No,count()
method,Paginator
Then it goes back to uselen(object_list)
. This makes it similar to Django’sQuerySet
More convenient to usecount()
Methods, if they exist.
Paginator.
`num_pages`
Total number of pages.
Paginator.
`page_range`
The range of page numbers, starting from 1, e.g[1, 2, 3, 4]
。
InvalidPage exceptions
_exception _InvalidPage
[source]
Exception, thrown when Paginator passes in an invalid page number.
Paginator.page()
Put back to throw an exception when the requested page is invalid (such as not an integer) or does not contain any objects. In general, captureInvalidPage
Exceptions are enough, but if you want to be more elaborate, you can catch one of the following two exceptions:
_exception _PageNotAnInteger
[source]
When topage()
Thrown when a value other than an integer is provided.
_exception _EmptyPage
[source]
When topage()
It is thrown when a valid value is provided, but there is no object on that page.
Both of these are exceptionsInvalidPage
So you can use simpleexcept InvalidPage
To deal with them.
Page objects
You don’t usually need to build manuallyPage
Objects – you can choose fromPaginator.page()
To get them.
_class _Page
(_object_list_, _number_, _paginator_)[source]
When callinglen()
Or when you iterate directly over a page, its behavior is similar toPage.object_list
Sequence of.
method
Page.
`has_next`()[source]
Returns True
if there’s a next page.
Page.
`has_previous`()[source]
If there is a previous page, return toTrue
。
Page.
`has_other_pages`()[source]
If there is a previous page_ Or_ Next page, back toTrue
。
Page.
`next_page_number`()[source]
Returns the page number of the next page. If the next page does not exist, throwInvalidPage
Abnormal.
Page.
`previous_page_number`()[source]
Returns the page number of the previous page. If the previous page does not exist, throwInvalidPage
Abnormal.
Page.
`start_index`()[source]
Returns the first object on the current page, relative to the sequence number of all objects in the paging list, starting from 1. For example, divide the list of five objects into two objects on each page, and the list of objects on the second pagestart_index()
Will return3
。
Page.
`end_index`()[source]
Returns the last object on the current page, relative to the sequence number of all objects in the paging list, starting from 1. For example, divide the list of five objects into two objects on each page, and the list of objects on the second pageend_index()
Will return4
。
attribute
Page.
`object_list`
A list of all objects on the current page.
Page.
`number`
The serial number of the current page, starting from 1.
Page.
`paginator`
dependentPaginator
Object.
translator:Django document collaborative translation teamOriginal text:Pagination。
This paper is based onCC BY-NC-SA 3.0Please keep the author’s signature and the source of the article.
Django document collaborative translation teamWe are short of staff. Interested friends can join us. It is totally public welfare. Communication group: 467338606.