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)