首页 > 解决方案 > 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": [
       …
    ]
}

标签: djangopython-3.xpaginationdjango-rest-framework

解决方案


你需要调用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()方法


推荐阅读