Python教程

python - 分页代码

本文主要是介绍python - 分页代码,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.  分页的基础 

views.py

 

    # 分页代码
    page = int(request.GET.get('page', 1))
    paeg_size = 10
    start = (page - 1) * paeg_size
    end = page * paeg_size

  # 查询结果输出 
    number_lits = models.Number.objects.filter(**data_dict).order_by('-price')[start:end]

 

2.  html

<nav aria-label="Page navigation">
              <ul class="pagination">
                    <li>
                      <a href="#" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                      </a>
                    </li>
                    <li><a href="?page=1">1</a></li>
                    <li><a href="?page=2">2</a></li>
                    <li><a href="?page=3">3</a></li>
                    <li><a href="?page=4">4</a></li>
                    <li><a href="?page=5">5</a></li>
                    <li>
                      <a href="#" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                      </a>
                    </li>
              </ul>
</nav>

 


 

 

正式分页代码 (不完整):

 

 # 分页代码
    page = int(request.GET.get('page', 1))
    paeg_size = 11  # 每页显示条数
    start = (page - 1) * paeg_size  # 开始数据
    end = page * paeg_size  #结束数据

    # 查询数据库中所有数据的  个数
    tot_count = models.Number.objects.filter(**data_dict).order_by('-price').count()
    # 输出结果
    number_lits = models.Number.objects.filter(**data_dict).order_by('-price')[start:end]

    # 总页码
    total_page_count, div = divmod(tot_count, paeg_size)
    if div:
        total_page_count + 1

    # 页码     page_steing = ''.join(page_ste_list) 变为安全必须得导包
    from django.utils.safestring import mark_safe
    page_ste_list = []
    for i in range(1, total_page_count + 1):
        ele = '<li><a href="?page={}">{}</a></li>'.format(i, i)
        page_ste_list.append(ele)
    # mark_safe() 需要导包
    page_steing = mark_safe(''.join(page_ste_list))

    return render(request, 'number_list.html', {'number_lits': number_lits, 'search_data':search_data, 'page_steing': page_steing})

 

这篇关于python - 分页代码的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!