三步实现Django Paginator分页的方法

Django提供了一个新的类来帮助管理分页数据,这个类存放在django/core/paginator.py.它可以接收列表、元组或其它可迭代的对象。本文将分三步介绍Django Paginator 分页的实现步骤

一、通过模型创建Subject

Django models

from django.db import models 
class Subject(models.Model):   
  """学科""”   
  no = models.AutoField(primary_key=True, verbose_name="编号")   
  name = models.CharField(max_length=31, verbose_name="名称")   
  intro = models.CharField(max_length=511, verbose_name="介绍")   
  def __str__(self):     
    return self.name   
  
  class Meta:     
    db_table = 'tb_subject'     
    verbose_name_plural = "学科"

二、通过view模块,要呈现到前端的数据

Django view 的配置

from django.shortcuts import render
from django.core.paginator import Paginator, InvalidPage, EmptyPage, PageNotAnInteger
from vote.models import Subject
def show_subject(request):
  """查询学科"""
  #查询Subject 表的所有数据
  subjects = Subject.objects.all().order_by("no”)
  #使用Paginator模块对数据分页,一页5条数据
  paginator = Paginator(subjects, 5)
  #使用request.GET.get()函数获取uri中的page参数的数值
  page = request.GET.get('page')
  try:
    #通过获取上面的page参数,查询此page是否为整数并且是否可用
    subject_obj = paginator.page(page)
  except PageNotAnInteger:
    subject_obj = paginator.page(1)
  except (EmptyPage, InvalidPage):
    subject_obj = paginator.page(paginator.num_pages)
  return render(request, "vote/subject.html", {'subject_list': subject_obj})

三、将view中的数据渲染到前端模版上

前端分页代码块:

<div class="pull-right" style="margin-right: 480px;margin-top: 0px”>
        <!― 分页功能-->
        <nav>
          <ul class="pagination”>
            <!― 分页功能前端的方向箭头代码-->
            {% if subject_list.has_previous %}
            <li class="enabled">
              <a href="?page={{ subject_list.previous_page_number }}" rel="external nofollow" aria-label="Previous">
                <span aria-hidden="true">«</span>
              </a>
            </li>
            {% endif %}
            <!― 分页功能显示页码的中间部分代码-->
            {% for page_num in subject_list.paginator.page_range %}
              {% if page_num == subject_list.number %}
                <li class="active">
                  <a href="#" rel="external nofollow" >
                    {{ page_num }}
                    <span class="sr-only">(current)</span>
                  </a>
                </li>
              {% else %}
                <li>
                  <a href="?page={{ page_num }}" rel="external nofollow" >{{ page_num }}
                    <span class="sr-only">(current)</span>
                  </a>
                </li>
              {% endif %}
            {% endfor %}
            <!― 分页功能末端的方向箭头代码-->
            {% if subject_list.has_next %}
            <li class="enabled">
              <a href="?page={{ subject_list.next_page_number }}" rel="external nofollow" aria-label="last">
                <span aria-hidden="true">»</span>
              </a>
            </li>
            {% endif %}
          </ul>
        </nav>
</div>

四、最终显示效果

三步实现Django Paginator分页的方法

相关推荐