如何在Django分页中显示JSON响应中的总页数? [英] How to show total pages in JSON response in Django Pagination?
问题描述
我目前正在Django Restful框架中进行分页.我已成功完成分页.但我面临的问题是"JSON响应中不包含有关查询中的页面总数的信息以及其他信息(如记录总数等)".如何在回复中包含此信息.我的view.py是
I am currently working on pagination in Django restful framework. I am successfully done with pagination. but the problem I am facing is that "JSON response does not include information about total pages in my query and other information like total records etc". how can I include this information in my response. my view.py is
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
#######################View all mobiles
@api_view(['GET'])
def getAll_Mobiles(request):
try:
Mobile_all = Mobile.objects.all()
paginator = Paginator(Mobile_all, 10)
page = request.GET.get('page')
try:
users = paginator.page(page)
except PageNotAnInteger:
users = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999),
# deliver last page of results.
users = paginator.page(paginator.num_pages)
serializer_context = {'request': request}
serializer = Mobile_Serializer(users,many=True,context=serializer_context)
return Response(serializer.data)
except Mobile.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
,我的API返回URL更改页面上的记录.但它没有给我回复信息.任何人都可以告诉我如何在响应中包含此信息.我将对此表示感谢.
and my API returns record on changing page in URL. but it does not give me response information. Can anybody please tell me how to include this information in response. I will be very thankful for this favour.
推荐答案
if serializer.data["hasPagination"]:
paginator = Paginator(result_serializer.data, settings.PAGE_SIZE)
page = request.GET.get('page', 1)
result = paginator.get_page(page)
return Response(data={
'results': result.object_list,
'total_records': paginator.count,
'total_pages': paginator.num_pages,
'page': result.number,
'has_next': result.has_next(),
'has_prev': result.has_previous()
}, status=status.HTTP_200_OK)
这篇关于如何在Django分页中显示JSON响应中的总页数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!