Django 之Paginator
Posted 小小菜_v
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django 之Paginator相关的知识,希望对你有一定的参考价值。
Django 之分页
django 框架自带分页的功能,需要调用模块 Paginator,实例如下:
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import JsonResponse
@csrf_exempt
def get_book_info(request):
"""
获取书籍信息
:param request
:return:
"""
try:
page_num = request.GET.get("pageNum")
page_size = request.GET.get("pageSize")
query_data = BookInfo.objects.filter(author="巴金").values()
total = query_data.count()
paginator = Paginator(query_data, page_size)
except (OSError):
return JsonResponse({"data": [], "total": 0}, safe=False)
# 校验 page_num是否为整数或者page_num大于页码数返回值为空
try:
contacts = paginator.page(page_num)
except PageNotAnInteger:
contacts = paginator.page(1)
except EmptyPage:
contacts = paginator.page(paginator.num_pages)
return JsonResponse({"data": list(contacts), "total": total}, safe=False)
以上是关于Django 之Paginator的主要内容,如果未能解决你的问题,请参考以下文章