Django的翻页API使用非常方便
shell api
在shell中使用一下:
from django.core.paginator import Paginator
from sign.models import Guest # 导入一个模型
guest_list = Guest.objects.all()
p = Paginator(guest_list, 2) # 创造一个每页2条数据的分页器
p.count # 查看总数据
p.page_range # 查看一共分多少页
range(1, 7)
page1 = p.page(1) # 获取第一页数据
page1
<page1 of 6>
page1.object_list # 当前页的对象
[<Guest: sen>, <Guest: 燃墟>]
for p in page1:
print(p.realname)
"sen"
"燃墟"
page1.start_index() # 获取本页的第一条数据
page1.end_index() # 本页的最后一条数据
page1.has_previous()
False
page1.has_next() # 是否有下一页
True
page1.previous_page_number() # 上一页
报错
page1.has_other_page() # 是否有其他页
True
视图函数用例
视图函数:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# 要导入这三个
def list(request):
object_list = Post.objects.all()
paginator = Paginator(object_list, 3) # 选择分页的对象, 分页数量
page = request.GET.get("page") #获取page参数
try:
posts = paginator.get(page)
except PageNotAnInteger: # 如果不是数字
posts = paginator.page(1) # 返回第一页
except EmptyPage:
posts = paginator.page(paginator.num_pages) # 如果大于最大页数,返回最后一页
return render(request, "list.html", {"posts", posts, "page", page})
html页面
page.html
<div class="pagination">
<span class="material-icons">
{% if page.has_previous %}
<a href="?page=1">« first</a>
<a href="?page={{ page.previous_page_number }}">Previous</a>
{% endif %}
<span class="active">
Page {{ page.number }} of {{ page.paginator.num_pages }}
</span>
{% if page.has_next %}
<a href="?page={{ page.next_page_number }}">Next</a>
<a href="?page={{ page.paginator.num_pages }}">last »</a>
{% endif %}
</span>
</div>