Recent projects used in the paging function, Django comes with Paginator to achieve a simple paging.
The first step, import Paginator and related abnormalities module
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
Paginator: Paging object
PageNotAnInteger: Page not express pass over the Integer type throws the exception.
EmptyPage: indicates when the page is out of range (i.e., the page number is too large or too small, the data is empty) raises the exception.
Written in the second step, the paging function
Wherein: data is data, list type. start is the number of pages, int type. Limit the number of page, int type
p = Paginator(data, limit)
p is the paging object, its attributes comprises:
count: Returns a list of objects (data) length
num_pages: Returns the total number of pages
page_range: return Page List
response = {} p = Paginator(data, limit) try: new_data = p.page(start) except PageNotAnInteger as e: print e # Page is not an integer back to the first page new_data = p.page(1) except EmptyPage as e: print e total_num = p.num_pages if start > total_num: # Returns the last page number is larger than a total data returned new_data = p.page(total_num) else: new_data = p.page(1) print new_data, 'new_data' response['info'] = new_data.object_list
new_data page as an object, which is the common attributes:
- object_list: The same refers to the object list, but only contains the current object page
- number: current page's page
- paginator: refer to the corresponding object tab (Paginator)