您的位置:首页 > 编程语言 > Go语言

django实现分页

2017-05-27 14:20 423 查看

分页实现思路:

1.接口拉取库内数据,进行分页
2.页面实现分页组件,切换不同链接

一、接口实现:

from django.core.paginator import Paginator

p=Paginator(report.objects.order_by("-endtime"),20)  #对数据进行分页,默认每页20条数据
pagenums=p.num_pages


说明:
1.使用Paginator类进行分页,使用方法【Paginator(列表,一页显示的内容个数)】
例如:Paginator(report.objects.order_by("-endtime"),20)
入参列表可以是个models查询后的django QuerySet对象

2.Paginator对象的num_pages返回查询结果的总个数,可以用来展示分页的页数

更多Paginator的操作,可以参考下面的 文档:
http://www.jb51.net/article/66735.htm

二、html分页展示

<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>

<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<ul class="pagination" >
{% if pagenum > 1%}
<li><a href="{% url 'reports' %}?pagenum={{ pagenum|add:-1 }}">«</a></li>
{% else %}
<li><a href="">«</a></li>
{% endif %}
{% for currentpagenum in  reportinfos.pagenums%}
{% if currentpagenum == pagenum %}
<li><a href="{% url 'reports' %}?pagenum={{ currentpagenum }}" style="background-color: #5bc0de">{{ currentpagenum }}</a></li>
{% else %}
<li><a href="{% url 'reports' %}?pagenum={{ currentpagenum }}">{{ currentpagenum }}</a></li>
{% endif %}
{% endfor %}
{% if pagenum < reportinfos.maxpagenum %}
<li><a href="{% url 'reports' %}?pagenum={{ pagenum|add:1 }}">»</a></li>
{% else %}
<li><a href="">»</a></li>
{% endif %}
</ul>
</body>

</html>


说明:
1.分页使用了bootstrap的样式,所以引入了相关的js
2.分页的按钮的连接点击跳转到对应页面加参数pagenum(/xxx?pagenum=xxx)(html中的pagenum为渲染时传入的总页码个数)
3.前一页和后一页按钮,判断了是否超过最小页码1和最大页码边界,如果不超过跳转链接在当前页码下+1或-1,如果超出边界则不能点击

这里应用了django模板中变量的加减法,加法【{{ 变量名|add:数字 }}】,减法【{{ 变量名|add:-数字 }}】
减法只是数字前加负号,注意|和add以及:左右没有空格
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: