python - 在 Django Rest 框架分页中添加新值

标签 python django django-rest-framework django-pagination

我想在分页返回时添加“isSuccess”。

例如,

{
    "count": 1234,
    "next": "http://mydomain/?page=2",
    "previous": null,
    "isSuccess" : 'Success'  # <---- this one
    "results": [
        {
          'id':123,
           'name':'abc'
        }, 
        {
          'id':234,
          'name':'efg'
        },
         ...
    ]
}

我找到了this way但它没有用。 如何在 Django 分页返回中添加新值?

这是我的尝试:

class Testing(generics.GenericAPIView):
    queryset = Problem.objects.all()
    serializer_class = userSerializer
    pagination_class = userPagination

    def get(self, request):
        queryset = self.get_queryset()
        page = self.request.query_params.get('page')

        if page is not None:
            paginate_queryset = self.paginate_queryset(queryset)
            serializer = self.serializer_class(paginate_queryset, many=True)

            tmp = serializer.data
            tmp['isSuccess'] = 'Success'

            return self.get_paginated_response(tmp)

最佳答案

尝试一下,不要将 isSuccess 添加到 serializer.data,而是将其添加到 get_pagination_response().data

def get(self, request):
    queryset = self.get_queryset()
    page = self.request.query_params.get('page')

    if page is not None:
        paginate_queryset = self.paginate_queryset(queryset)
        serializer = self.serializer_class(paginate_queryset, many=True)

        tmp = serializer.data
        # tmp['isSuccess'] = 'Success'

        response = self.get_paginated_response(tmp)
        response.data['isSuccess'] = "Success"

        return Response(data=response.data, status=status.HTTP_200_OK)

    return Response(data="No Page parameter found", status=status.HTTP_200_OK)

响应将类似于

{
    "count": 1234,
    "next": null,
    "previous": null,
    "results": [
        {
          'id':123,
           'name':'abc'
        },
        ...
    ],
    "isSuccess" : 'Success'
}

关于python - 在 Django Rest 框架分页中添加新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67444842/

相关文章:

django/taggit-错误 : MyData objects need to have a primary key value before you can access their tags

python - 在 Plone 模板中处理表单提交

python - 在 mysql/python 中转义整个字符串

python - 检查 number 是否连续包含 x 个相等的数字

python - API 响应文本到 JSON

python - Django 休息框架 : Nested Serializer Dynamic Model Fields

python - DRF 序列化器将某些模型实例的字段更改为 read_only

python - 如何在 Vim 中为 Python 代码切换注释和取消注释

python - Django 内部服务器错误而不是 404

django - 如何从Django的请求中获取多值键的所有值。