首页 > 其他分享 >django分页器

django分页器

时间:2023-03-09 13:12:23浏览次数:32  
标签:count 分页 self django current num test page

分页器

Django分页器

Django自带分页器,但是不太好用,所以可以直接自定义一个分页器供项目使用。

# 1. 在项目下建一个utils文件夹
# 2. 建立一个py文件,MyPage.py(自己随意命名),代码内容如下:

class Pagination(object):
    def __init__(self, current_page, all_count, per_page_num=2, pager_count=11):
        """
        封装分页相关数据
        :param current_page: 当前页
        :param all_count:    数据库中的数据总条数
        :param per_page_num: 每页显示的数据条数
        :param pager_count:  最多显示的页码个数
        """
        try:
            current_page = int(current_page)
        except Exception as e:
            current_page = 1
 
        if current_page < 1:
            current_page = 1
 
        self.current_page = current_page
 
        self.all_count = all_count
        self.per_page_num = per_page_num
 
        # 总页码
        all_pager, tmp = divmod(all_count, per_page_num)
        if tmp:
            all_pager += 1
        self.all_pager = all_pager
 
        self.pager_count = pager_count
        self.pager_count_half = int((pager_count - 1) / 2)
 
    @property
    def start(self):
        return (self.current_page - 1) * self.per_page_num
 
    @property
    def end(self):
        return self.current_page * self.per_page_num
 
    def page_html(self):
        # 如果总页码 < 11个:
        if self.all_pager <= self.pager_count:
            pager_start = 1
            pager_end = self.all_pager + 1
        # 总页码  > 11
        else:
            # 当前页如果<=页面上最多显示11/2个页码
            if self.current_page <= self.pager_count_half:
                pager_start = 1
                pager_end = self.pager_count + 1
 
            # 当前页大于5
            else:
                # 页码翻到最后
                if (self.current_page + self.pager_count_half) > self.all_pager:
                    pager_end = self.all_pager + 1
                    pager_start = self.all_pager - self.pager_count + 1
                else:
                    pager_start = self.current_page - self.pager_count_half
                    pager_end = self.current_page + self.pager_count_half + 1
 
        page_html_list = []
        # 添加前面的nav和ul标签
        page_html_list.append('''
                    <nav aria-label='Page navigation>'
                    <ul class='pagination'>
                ''')
        first_page = '<li><a href="?page=%s">首页</a></li>' % (1)
        page_html_list.append(first_page)
 
        if self.current_page <= 1:
            prev_page = '<li class="disabled"><a href="#">上一页</a></li>'
        else:
            prev_page = '<li><a href="?page=%s">上一页</a></li>' % (self.current_page - 1,)
 
        page_html_list.append(prev_page)
 
        for i in range(pager_start, pager_end):
            if i == self.current_page:
                temp = '<li class="active"><a href="?page=%s">%s</a></li>' % (i, i,)
            else:
                temp = '<li><a href="?page=%s">%s</a></li>' % (i, i,)
            page_html_list.append(temp)
 
        if self.current_page >= self.all_pager:
            next_page = '<li class="disabled"><a href="#">下一页</a></li>'
        else:
            next_page = '<li><a href="?page=%s">下一页</a></li>' % (self.current_page + 1,)
        page_html_list.append(next_page)
 
        last_page = '<li><a href="?page=%s">尾页</a></li>' % (self.all_pager,)
        page_html_list.append(last_page)
        # 尾部添加标签
        page_html_list.append('''
                                           </nav>
                                           </ul>
                                       ''')
        return ''.join(page_html_list)

# 3. 视图层调用
def testadd_func(request):
    # 1. 定义查找出来的数据
    test_queryset = models.Test.objects.all()
    # 2. 导入分页器
    from utils.mypage import Pagination
    # 3. 获取前台用户的页码
    current_page = request.GET.get('page')
    # 4. 传入当前页码与总数据量两个变量,current_page由第三步获取来,总数据量使用count()即可
    page_obj = Pagination(current_page=current_page, all_count=test_queryset.count())
    # 5. 对页码分页,最后将这个page_queryset传到前台,page_queryset就是展示的数据
    page_queryset = test_queryset[page_obj.start:page_obj.end]
    return render(request, 'testadd.html', locals())

# 4. 模板层
<div class="container">
    <div class="row">
        <h1 class="text-center">展示</h1>
        <div class="col-md-8 col-md-offset-5">
            {# 使用后台传入的数据,for循环展示 #}
            {% for obj in page_queryset %}
                <p>{{ obj.name }}</p>
            {% endfor %}
        </div>
        {# 显示页码 #}
        {{ page_obj.page_html | safe }}
    </div>
</div>

效果如下:

分页器的推导过程

  • 下面是分页器的推导过程,主要学习其逻辑,如果要使用的话直接使用上面的自定义分页器即可

    1. ORM是可以使用切片处理的(限正数),这时我们想看前10条数据,代码如下:
def test_func(request):
    test_queryset = models.Test.objects.all()[0:10]
    return render(request, 'test.html', locals())

image

2. 如果想看10到20页的数据,代码如下:
test_queryset = models.Test.objects.all()[10:20]
3. 所以,如果想看分页,就要想办法让切片动态变化
'''
1. 先确定每页展示多少条数据(10条)
2. 每页起始位置与终止位置
'''
def test_func(request):
    page_num = 10  # 每页展示的数据条数
    start_num = 0  # 起始展示位置
    end_num = 10  # 终止位置
    test_queryset = models.Test.objects.all()[start_num:end_num]
    return render(request, 'test.html', locals())

上面的代码将起始位置与终止位置进行了参数化,下个目标开始研究起始位置与终止位置与页数之间的数学关系。

page_num = 5  # 每页展示的数据条数
current_page         start_num          end_num
  当前页数             起始位置          终止位置
     1                   0                 5
     2                   5                 10
     3                   10                15
     4                   15                20
     5                   20                25
    ...                 ...               ...

# 由上面推导可以得出
start_num = (current_page - 1) * page_num
end_num = current_page * page_num

现在start_num有了,end_num有了,但是用户想访问哪一页还没有,这时就需要前端传入了,前端可以使用?形式传入

def test_func(request):
    page_num = 10  # 每页展示的数据条数
    current_page = request.GET.get('page', 1)  # 拿到前端页面,默认为1
    try:  # 如果用户输入为非数字导致int报错,直接让用户访问第一页
        current_page = int(current_page)
    except Exception:
        current_page = 1
    start_num = (current_page - 1) * page_num  # 起始展示位置
    end_num = current_page * page_num  # 终止位置
    test_queryset = models.Test.objects.all()[start_num:end_num]
    return render(request, 'test.html', locals())

image

此时需要添加用户可以点的页码,但又涉及一个问题,总页码应该是多少

per_page_num=10  all_count=100  page_num=10  # 如果有100条数据,每页展示10条,需要10页
per_page_num=10  all_count=101  page_num=11  # 如果有101条数据,每页展示10条,需要11页
per_page_num=10  all_count=99   page_num=10  # 如果有91条数据,每页展示10条,需要10页
现在需要使用代码,计算出需要使用多少页,这时候需要使用divmod这个内置函数,代码变形如下:
# 1. 视图层代码
def test_func(request):
    page_num = 10  # 每页展示的数据条数
    test_queryset = models.Test.objects.all()
    all_count = test_queryset.count()  # 总数据条数
    all_page_num, more = divmod(all_count, page_num)  # 取得数也余数
    # 当余数不为0时,则得数加1就是总页码
    if more:
        all_page_num += 1
    # 由于模板语法没有range功能,但还需要循环产生很多分页标签,所以考虑使用后端生成,再传到前端
    html_str = ''
    for i in range(1, all_page_num + 1):
        html_str += f'<li><a href="?page={i}">{i}</a></li>'
    current_page = request.GET.get('page', 1)  # 拿到前端页面,默认为1
    try:
        current_page = int(current_page)
    except Exception:
        current_page = 1
    start_num = (current_page - 1) * page_num  # 起始展示位置
    end_num = current_page * page_num  # 终止位置
    test_queryset = test_queryset[start_num:end_num]
    return render(request, 'test.html', locals())

# 2. 模板层代码
<div class="container">
    <div class="row">
        <h1 class="text-center">展示</h1>
        <div class="col-md-8 col-md-offset-5">
            {% for obj in test_queryset %}
                <p>{{ obj.name }}</p>
            {% endfor %}
        </div>
    </div>


<nav aria-label="Page navigation" class="text-center">
  <ul class="pagination">
    <li>
      <a href="#" aria-label="Previous">
        <span aria-hidden="true">&laquo;</span>
      </a>
    </li>
        {{ html_str|safe }}
    <li>
      <a href="#" aria-label="Next">
        <span aria-hidden="true">&raquo;</span>
      </a>
    </li>
  </ul>
</nav>
</div>

展示样式:

此时每页都可以使用,下一个阶段需要解决展示问题,页面不可以一次性全部展示出来。
页面的设计一般都是奇数,这样以中心页码进行分割,两边是对称的,比较美观。
思路,如果我要展示11个页码,那就可以以当前页码为基准,左边展示5个页码,右边展示5个页码,比如,当前页码为7,那页面展示应为:
2 3 4 5 6 7 8 9 10 11 12
代码如下:

def test_func(request):
    page_num = 10  # 每页展示的数据条数
    test_queryset = models.Test.objects.all()
    all_count = test_queryset.count()  # 总数据条数
    all_page_num, more = divmod(all_count, page_num)  # 取得数也余数
    current_page = request.GET.get('page', 1)  # 拿到前端页面,默认为1
    try:
        current_page = int(current_page)
    except Exception:
        current_page = 1
    # 当余数不为0时,则得数加1就是总页码
    if more:
        all_page_num += 1
    # 由于模板语法没有range功能,但还需要循环产生很多分页标签,所以考虑使用后端生成,再传到前端
    html_str = ''
    for i in range(current_page - 5, current_page + 6):  # 因为顾左不顾右,所以右侧是+6
        
        html_str += f'<li class="active"><a href="?page={i}">{i}</a></li>'
    start_num = (current_page - 1) * page_num  # 起始展示位置
    end_num = current_page * page_num  # 终止位置
    test_queryset = test_queryset[start_num:end_num]
    return render(request, 'test.html', locals())

效果有了,但是还有BUG,会显示负数,且页数最大上限也会超过总页数

下一点步就是解决负数问题:

def test_func(request):
    page_num = 10  # 每页展示的数据条数
    test_queryset = models.Test.objects.all()
    all_count = test_queryset.count()  # 总数据条数
    all_page_num, more = divmod(all_count, page_num)  # 取得数也余数
    current_page = request.GET.get('page', 1)  # 拿到前端页面,默认为1
    try:
        current_page = int(current_page)
    except Exception:
        current_page = 1
    # 当余数不为0时,则得数加1就是总页码
    if more:
        all_page_num += 1
    # 由于模板语法没有range功能,但还需要循环产生很多分页标签,所以考虑使用后端生成,再传到前端
    html_str = ''
    curr_num = current_page  # 这里如果不使用新变量赋值,则会影响前台页面显示的active效果
    if curr_num < 6:  # 如果值小于6,则就赋值为6
        curr_num = 6
    elif curr_num + 6 > all_page_num:   # 如果右侧+6后大于总页码,则使总页面+6后大于总页码+1就可以了
        curr_num = all_page_num - 5  # 比如我的总页码是100000,那for循环中的右侧页码最大是100001,顾左不顾右,所以要大1个数
    for i in range(curr_num - 5, curr_num + 6):  # 因为顾左不顾右,所以右侧是+6
        if current_page == i:  # 如果页码是用户选择的,则加一个active效果
            print(curr_num)
            html_str += f'<li class="active"><a href="?page={i}">{i}</a></li>'
        else:  # 否则没有active效果
            html_str += f'<li><a href="?page={i}">{i}</a></li>'
    start_num = (current_page - 1) * page_num  # 起始展示位置
    end_num = current_page * page_num  # 终止位置
    test_queryset = test_queryset[start_num:end_num]
    return render(request, 'test.html', locals())

此时显示如下:

  • 分页器大概逻辑就是这些了,还有前进后退的功能没有加,也没有什么必要加了,大概逻辑懂了就可以了。

标签:count,分页,self,django,current,num,test,page
From: https://www.cnblogs.com/smyz/p/17197631.html

相关文章