1 核心类Paginator的使用
参考资料:https://www.cnblogs.com/kongzhagen/p/6640975.html
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import os
from django.core.paginator import Paginator
objects = ['john','paul','george','ringo','lucy','meiry','checy','wind','flow','rain']<br>
p = Paginator(objects,3) # 3条数据为一页,实例化分页对象
print p.count # 10 对象总共10个元素
print p.num_pages # 4 对象可分4页
print p.page_range # xrange(1, 5) 对象页的可迭代范围
page1 = p.page(1) # 取对象的第一分页对象
print page1.object_list # 第一分页对象的元素列表['john', 'paul', 'george']
print page1.number # 第一分页对象的当前页值 1
page2 = p.page(2) # 取对象的第二分页对象
print page2.object_list # 第二分页对象的元素列表 ['ringo', 'lucy', 'meiry']
print page2.number # 第二分页对象的当前页码值 2
print page1.has_previous() # 第一分页对象是否有前一页 False
print page1.has_other_pages() # 第一分页对象是否有其它页 True
print page2.has_previous() # 第二分页对象是否有前一页 True
print page2.has_next() # 第二分页对象是否有下一页 True
print page2.next_page_number() # 第二分页对象下一页码的值 3
print page2.previous_page_number() # 第二分页对象的上一页码值 1
print page2.start_index() # 第二分页对象的元素开始索引 4
print page2.end_index() # 第2分页对象的元素结束索引 6
- Paginator, EmptyPage, PageNotAnInteger的组合使用
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render
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(request, 'list.html', {'contacts': contacts})
参考资料二:https://www.cnblogs.com/wupeiqi/articles/5246483.html
- Paginator的扩展
Django自带的Paginator的功能有限,可以对Paginator进行扩展,比如自定义显示的页码数。
class CustomPaginator(Paginator):
def __init__(self, current_page, max_pager_num, *args, **kwargs):
"""
:param current_page: 当前页
:param max_pager_num:最多显示的页码个数
:param args:
:param kwargs:
:return:
"""
self.current_page = int(current_page)
self.max_pager_num = max_pager_num
super(CustomPaginator, self).__init__(*args, **kwargs)
def page_num_range(self):
# 当前页面
# self.current_page
# 总页数
# self.num_pages
# 最多显示的页码个数
# self.max_pager_num
print(1)
if self.num_pages < self.max_pager_num:
return range(1, self.num_pages + 1)
print(2)
part = int(self.max_pager_num / 2)
if self.current_page - part < 1:
return range(1, self.max_pager_num + 1)
print(3)
if self.current_page + part > self.num_pages:
return range(self.num_pages + 1 - self.max_pager_num, self.num_pages + 1)
print(4)
return range(self.current_page - part, self.current_page + part + 1)
- 自定义分页功能
如果扩展还不能满足需求,可以自定义Paginator
参考资料:https://blog.csdn.net/lzp215lzp/article/details/77203770
网友评论