Django有自带的分页器,可以将数据分在不同的页面中,并提供一些属性和方法实现对分页数据的操作。分页功能的类位于django/core/paginator.py中。
常用方法
# 分页器 # paginator分页器对象(obj,每页条数) paginator = Paginator(book_list, 3) ################常用方法################# print("count:", paginator.count) # 数据总数 print("num_pages", paginator.num_pages) # 总页数 print("page_range", paginator.page_range) # 页码的列表 #################提取某一页具体数据的两种方式################# # 方式1 page1 = paginator.page(1) # 第1页的page对象 for i in page1: # 遍历第1页的所有数据对象 print(i) # 方式2 print(page1.object_list) # 第1页的所有数据
实例代码
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <body> <h3>图书列表</h3> <ul> {% for book_obj in current_page %} <li>{{ book_obj.title }}:{{ book_obj.price }}</li> {% endfor %} </ul> <nav aria-label="Page navigation"> <ul class="pagination"> {# 上一页#} {% if current_page.has_previous %} <li> <a href="?page={{ current_page.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">上一页</span> </a> </li> {% else %} {# 如果没有上一页了,就把标签禁止,且没有连接#} <li class="disabled"> <a href="" aria-label="Previous"> <span aria-hidden="true">上一页</span> </a> </li> {% endif %} {# 中间的页码#} {% for page in page_range %} {# 如果循环的页码等于当前的页码,就添加active#} {% if current_page_num == page%} <li class="active"><a href="?page={{ page }}">{{ page }}</a></li> {% else %} <li><a href="?page={{ page }}">{{ page }}</a></li> {% endif %} {% endfor %} {# 下一页#} {% if current_page.has_next %} <li> <a href="?page={{ current_page.next_page_number }}" aria-label="Next"> <span aria-hidden="true">下一页</span> </a> </li> {% else %} {# 如果没有下一页了,就把标签禁止,且没有连接#} <li class="disabled"> <a href="" aria-label="Next"> <span aria-hidden="true">下一页</span> </a> </li> {% endif %} </ul> </nav> </body> </html>
views.py
from django.shortcuts import render from app01.models import * from django.core.paginator import Paginator # Create your views here. def index(request): """ 批量导入数据到数据库 book_list=[] for i in range(100): book=Book(title="book%s"%i,price=i*i) book_list.append(book) Book.objects.bulk_create(book_list) :param request: :return: """ # 拿到所有的数据书籍 book_obj_list = Book.objects.all() # 生成分页器对象 paginator = Paginator(book_obj_list, 3) # 获取浏览器端请求的页码,需要设置默认值 current_page_num = int(request.GET.get('page', 1)) # 当前页的所有书对象 current_page = paginator.page(current_page_num) # 页码列表,可迭代 # 分页过多,需要用条件判断显示的页码 if paginator.num_pages > 11: # 11就是显示的固定个数 if current_page_num - 5 < 1: # 接近最小页码时,固定页码,否则会出现负数 page_range = range(1, 12) elif current_page_num + 5 > paginator.num_pages: # 接近最大页码时,根据最大页码限制页码数,否则会出现不存在的页码 page_range = range(paginator.num_pages - 10, paginator.num_pages + 1) else: page_range = range(current_page_num - 5, current_page_num + 6) # 其他情况,显示当前的挨着的几个 else: page_range = paginator.page_range # 页码总数不足时,显示全部,即不会超宽 return render(request, 'index.html', locals())