settings.py
# 自定义参数
EACH_PAGE_OF_NUMBER = 2
进入交互式命令
python manage.py shell
开始学习paginator
>>> from mysite.models import * #将models中的模型导入
>>> products = Product.objects.all() #获取到Product模型中的所有对象
>>> products #查看products中有哪些对象
<QuerySet [<Product: <Media:N3 纳米模板>>, <Product: <Media:超薄框>>, <Product: <Media:智能钢网柜>>]>
>>> content_list = products
>>> from django.core.paginator import Paginator #导入页码器
>>> from django.conf import settings #从setting中的导入设置的页码数量
>>> settings.EACH_PAGE_OF_NUMBER #查看设置的页码数目是多少
2
>>> paginator = Paginator(content_list, settings.EACH_PAGE_OF_NUMBER) #根据设置的页码数量,获取分页对象
>>> page_num =1 # 设置要看是第几页的内容
>>> page_of_content = paginator.get_page(page_num) #获取到page_num这个对象
>>> page_of_content #查看page_num这个对象
<Page 1 of 2>
>>> page_of_content.object_list #查看设置的这一页中有哪些内容
<QuerySet [<Product: <Media:N3 纳米模板>>, <Product: <Media:超薄框>>]>
>>> page_of_content.number #获取当前所在的页码
1
>>> page_of_content.paginator.num_pages #获取分页器一共分了多少页
2
>>>
PS:视图中加入分页器的函数使用
def get_paginator_list_common_data(req, content_list):
paginator = Paginator(content_list, settings.EACH_PAGE_OF_NUMBER)
page_num = req.GET.get('page', 1) # 获取url的页面参数(GET请求)
page_of_content = paginator.get_page(page_num)
current_page_num = page_of_content.number # 获取当前页码
# 获取当前页码前后各2页的页码范围
page_range = list(range(max(current_page_num - 2, 1), current_page_num)) + \
list(range(current_page_num, min(current_page_num + 2, paginator.num_pages) + 1))
# 加上省略页码标记
if page_range[0] - 1 >= 2:
page_range.insert(0, '...')
if paginator.num_pages - page_range[-1] >= 2:
page_range.append('...')
# 加上首页和尾页
if page_range[0] != 1:
page_range.insert(0, 1)
if page_range[-1] != paginator.num_pages:
page_range.append(paginator.num_pages)
context = dict()
context['content'] = page_of_content.object_list # 获取这一页有多少个内容,结果是一个类似于列表
context['page_of_content'] = page_of_content
context['page_range'] = page_range
return context
网友评论