【发布时间】:2019-09-29 06:04:05
【问题描述】:
对于我的 API,我使用的是 api_view 装饰器。分页问题(JSON 响应)。我得到了没有“分页块”的响应:
[
{
"id": 18,
"name": "Monitor Acer Test",
"price": "2212.00",
"stock": 21,
"image": "/media/9hq.webp",
"available": true
},
{
"id": 17,
"name": "Monitor LG Test",
"price": "2512.00",
"stock": 10,
"image": "/media/811AFxM28YL._SX425_.jpg",
"available": true
}
]
我也尝试过覆盖默认的 PageNumberPagination,它可以工作,但仍然没有“分页块”
我的 api 视图(查看 GET 示例 > 其他):
@csrf_exempt
@api_view(['GET', 'POST',])
@permission_classes([AllowAny, ])
def product(request):
item = request.data
if request.method == 'POST':
serializer = ProductSerializer(data=item)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response({"message": "Product created!", "data": request.data}, status=status.HTTP_201_CREATED)
else:
all_obj = Product.objects.filter(available=True)
if len(all_obj) > 0:
paginator = PageNumberPagination()
result_page = paginator.paginate_queryset(all_obj, request)
serializer = ProductSerializer(result_page, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response({"message": "There is no created items!"}, status=status.HTTP_200_OK)
我的设置.py:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',),
'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.AllowAny',],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 2
}
预期结果:
{
"count": 1023
"next": "https://api.example.org/accounts/?page=5",
"previous": "https://api.example.org/accounts/?page=3",
"results": [
…
]
}
【问题讨论】:
标签: django python-3.x pagination django-rest-framework