如何将所有元数据包装到“元”属性中?

问题描述 投票:0回答:2

所以我有一个分页的结果列表。以下是 DRF 默认的格式化方式:

{
    "count": 1023
    "next": "https://api.example.org/accounts/?page=5",
    "previous": "https://api.example.org/accounts/?page=3",
    "results": [
       …
    ]
}

如何将所有元数据包装到“元”属性中,以便响应如下所示:

{
    "meta": {
        "count": 1023
        "next": "https://api.example.org/accounts/?page=5",
        "previous": "https://api.example.org/accounts/?page=3",
    },
    "results": [
       …
    ]
}

编辑:感谢阿拉斯代尔的回答。我是这样做的:

from rest_framework import pagination
from rest_framework.response import Response

class CustomPagination(pagination.LimitOffsetPagination):

  def get_paginated_response(self, data):
    return Response({
      'meta': {
        'next': self.get_next_link(),
        'previous': self.get_previous_link(),
        'count': self.count
      },
      'results': data
    })
django django-rest-framework
2个回答
2
投票

您需要实现自定义分页样式以将所有元数据包装到元属性中。

Step-1 实现自定义分页类:

首先,我们将实现一个自定义分页类

WrappedMetadataPagination
,它将继承自
pagination.LimitOffsetPagination
。在此,我们将覆盖
get_paginated_response()
并指定我们的自定义分页输出样式。

class WrappedMetadataPagination(pagination.LimitOffsetPagination):
    """
    This custom pagination class wraps the metadata about the results 
    like 'next', 'previous' and 'next' keys into a dictionary with key as 'meta'.
    """

    def get_paginated_response(self, data):
        return Response({
            'meta': { # wrap other keys as dictionary into 'meta' key
                'next': self.get_next_link(),
                'previous': self.get_previous_link(),
                'count': self.count
            },
            'results': data
        })

第2步在DRF设置中设置自定义类:

实现自定义类后,您需要在 DRF 设置中指定此自定义分页类。

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'my_project.my_app.pagination.WrappedMetadataPagination', # specify the custom pagination class
...       
}

0
投票

您可以使用 drf-pagination-meta-wrap pkg。适用于所有类型的分页并且高度可定制

© www.soinside.com 2019 - 2024. All rights reserved.