【问题标题】:How do I change the 'results' fieldname in Django REST Framework to something else?如何将 Django REST Framework 中的“结果”字段名更改为其他名称?
【发布时间】:2018-04-17 20:11:54
【问题描述】:

我正在使用 Django REST 框架和 PageNumberPagination 类来序列化模型内容。输出如下:

{
"count": 1,
"next": null,
"previous": null,
"results": [
    {
        "id": 1,
        "foo": "foo",
        "bar": "bar"
    }
}

如何将输出中的 results 字段名更改为其他名称?喜欢foo_resultsauthors 或任何我想要的?

我正在使用通用视图集和序列化器。

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    通过 docs custom-pagination-styles 你可以试试

    class CustomPagination(pagination.PageNumberPagination):
    
        def get_paginated_response(self, data):
    
            return Response({
                'next': self.get_next_link(),
                'previous': self.get_previous_link()
                'count': self.page.paginator.count,
                'WHATDOYOUWANTHERE': data,
                # ^^^^^^^^^^
            })
    

    如果您想在分页器的设置更新数据中将其设置为默认值

    REST_FRAMEWORK = {
        'DEFAULT_PAGINATION_CLASS': 'my_project.core.pagination.CustomPagination',
         #                      ^^^ CHANGE PATH TO YOUR PAGINATOR CLASS ^^^
        'PAGE_SIZE': 100
    }
    

    或通过参数modifying-the-pagination-style 包含到您的视图中

    pagination_class = CustomPagination
    

    【讨论】:

    • 这就是我的方式。非常感谢!
    • 很高兴为您提供帮助
    【解决方案2】:

    官方documentation有例子。

    创建一个自定义分页类,如示例中所示:

    class CustomPagination(pagination.PageNumberPagination):
        def get_paginated_response(self, data):
            return Response({
                'links': {
                    'next': self.get_next_link(),
                    'previous': self.get_previous_link()
                },
                'count': self.page.paginator.count,
                'results''foo_results': data
            })

    在您的settings.py 中输入以下内容:

    REST_FRAMEWORK = {
        'DEFAULT_PAGINATION_CLASS': 'path.to.your.custom.pagination',
        'PAGE_SIZE': 100
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-22
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 2021-04-09
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      相关资源
      最近更新 更多