django - Django REST:JSON 响应中没有分页块 (PageNumberPagination)
问题描述
对于我的 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 示例> else):
@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": [
…
]
}
解决方案
你需要调用get_paginated_response()
方法,
@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)
paginator = PageNumberPagination()
result_page = paginator.paginate_queryset(all_obj, request)
if result_page is not None:
serializer = ProductSerializer(result_page, many=True)
return paginator.get_paginated_response(serializer.data)
else:
serializer = ProductSerializer(all_obj, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
注意不要调用len(queryset)
,它会导致N
数据库连接数。改用count()
方法
推荐阅读
- firebase - Flutter 用户注册存储数据
- javascript - 如何使用 Python(BS4?)解析 Javascript 呈现的网页
- javascript - Vue.js: Defining computed environment variables in vue.config.js (vue cli 3)
- android - 跨活动处理服务和发送数据
- docker - 如何在 Docker 容器内启用wiringpi GPIO控制
- gmail-api - 何时生成新的 Gmail API 历史 ID
- javascript - 当按钮点击错误时发送通知
- c# - 将类转换为类库并实例化
- linux - 如何以非交互式样式使用命令“at”
- svn - 如何关闭 Google Bitnami Subversion?