Django自身提供了一些类来实现管理分页,数据被分在不同的页面中,并带有“上一页/下一页”标签。这个类叫做Pagination,其定义位于 django/core/paginator.py 中。
paginator = Paginator(goods_list,8) # 把商品分成 8 个一页。 paginator.num_pages 一共多少页 paginator.page(page):第几页商品的信息 以下实例参考 def therapy_list(request): limit = request.GET.get('limit', 20) page = request.GET.get('page', 1) therapy_objects = Therapy.objects.filter(is_available=True) if therapy_objects.count() > 0: data = [{ 'id': x.id, 'name': x.name, 'price': x.price(), 'thumbnail': x.thumbnail.url, 'desc': x.tags, 'sales': TherapyOrder.objects.filter(arrangement__therapy=x).count() } for x in therapy_objects] else: data = [] pages = Paginator(data, limit) # 把数据分成20个一页 return JsonResponse({ 'status': '200', 'msg': '', 'data': pages.page(page).object_list if int(page) <= pages.num_pages else [] })