Django的分页

Posted qq849784670

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django的分页相关的知识,希望对你有一定的参考价值。

1.插入批量数据

    book_list = []
    for i in range(1,101):
        book = Book(title="book_%s"%i,price=i*i)
        book_list.append(book)
    Book.objects.bulk_create(book_list)

2.分页器的使用

    book_list = Book.objects.all()
    print(book_list)
    paginator = Paginator(book_list, 10)
    print(paginator.count)  #对象总数
    print(paginator.num_pages)  #分页数
    print(paginator.page_range) #range(1,11)
    page = paginator.page(5)    #第几页的数据
    for i in page:
        print(i)
    print(page.has_next())  #是否有下一页  True
    print(page.has_previous()) #是否有上一页
    print(page.next_page_number()) #下一页是第几页
    print(page.previous_page_number())  #上一页是第几页

3.服务器端

def index(request):
    book_list = Book.objects.all()
    paginator = Paginator(book_list,10)
    current_page_num = request.GET.get("page",1)
    current_page = paginator.page(current_page_num)
    return render(request,"index.html",{"current_page":current_page,"paginator":paginator,"current_page_num":int(current_page_num)})

4.前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
     <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<ul>
    {% for book in current_page %}
        <li>{{ book.title }}------{{ book.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="">上一页</a></li>
    {% endif %}
      {% for i in paginator.page_range %}
          {% if current_page_num == i %}
             <li class="active"><a href="?page={{ i }}">{{ i }}</a></li>
          {% else %}
              <li><a href="?page={{ i }}">{{ i }}</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="">下一页</a></li>
    {% endif %}

  </ul>
</nav>
</body>
</html>

 

以上是关于Django的分页的主要内容,如果未能解决你的问题,请参考以下文章

django 中的分页 - 原始查询字符串丢失

Django内置的分页模块

Django内置的分页模块

Django之路——10 django的分页组件

Django的分页和中间件

Django 第八篇Django自带的分页器