如何将根元素添加到json响应(Django-REST-框架)?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (55)

我试图确定使用django和django-rest-framework将根元素添加到所有json响应的最佳方法。

我认为添加自定义渲染器是实现我想实现的最好方法,这是我迄今为止所提出的:

from rest_framework.renderers import JSONRenderer

class CustomJSONRenderer(JSONRenderer):
#override the render method
def render(self, data, accepted_media_type=None, renderer_context=None):
    #call super, as we really just want to mess with the data returned
    json_str = super(CustomJSONRenderer, self).render(data, accepted_media_type, renderer_context)
    root_element = 'contact'

    #wrap the json string in the desired root element
    ret = '{%s: %s}' % (root_element, json_str) 

    return ret

现在棘手的部分是动态设置root_element基于render()被调用的视图。

提问于
用户回答回答于

为了后代,下面是最后的解决方案。它从原来的略有增长,因为它现在也重新分页分页结果。

此外,我应该在之前指出,JSON根元素的原因是与Ember前端解决方案集成。

串行:

from rest_framework.serializers import ModelSerializer
from api.models import Contact

class ContactSerializer(ModelSerializer):
    class Meta:
        model = Contact
        #define the resource we wish to use for the root element of the response
        resource_name = 'contact' 
        fields = ('id', 'first_name', 'last_name', 'phone_number', 'company')

渲染:

from rest_framework.renderers import JSONRenderer

class CustomJSONRenderer(JSONRenderer):
"""
    Override the render method of the django rest framework JSONRenderer to allow the following:
    * adding a resource_name root element to all GET requests formatted with JSON
    * reformatting paginated results to the following structure {meta: {}, resource_name: [{},{}]}

    NB: This solution requires a custom pagination serializer and an attribute of 'resource_name'
        defined in the serializer
"""
def render(self, data, accepted_media_type=None, renderer_context=None):
    response_data = {}

    #determine the resource name for this request - default to objects if not defined
    resource = getattr(renderer_context.get('view').get_serializer().Meta, 'resource_name', 'objects')

    #check if the results have been paginated
    if data.get('paginated_results'):
        #add the resource key and copy the results
        response_data['meta'] = data.get('meta')
        response_data[resource] = data.get('paginated_results')
    else:
        response_data[resource] = data

    #call super to render the response
    response = super(CustomJSONRenderer, self).render(response_data, accepted_media_type, renderer_context)

    return response

分页:

from rest_framework import pagination, serializers

class CustomMetaSerializer(serializers.Serializer):
    next_page = pagination.NextPageField(source='*')
    prev_page = pagination.PreviousPageField(source='*')
    record_count = serializers.Field(source='paginator.count')

class CustomPaginationSerializer(pagination.BasePaginationSerializer):
    # Takes the page object as the source
    meta = CustomMetaSerializer(source='*')
    results_field = 'paginated_results'
用户回答回答于

就个人而言,我想为每个对某个对象的api请求添加元数据,无论它是否分页。我也想简单地传入一个手动定义的字典对象。

调整自定义渲染器

class CustomJSONRenderer(renderers.JSONRenderer):
    def render(self, data, accepted_media_type=None, renderer_context=None):
        response_data = {}
        # Name the object list 
        object_list = 'results'
        try:
            meta_dict = getattr(renderer_context.get('view').get_serializer().Meta, 'meta_dict')
        except:
            meta_dict = dict()
        try:
            data.get('paginated_results')
            response_data['meta'] = data['meta']
            response_data[object_list] = data['results']
        except:
            response_data[object_list] = data
            response_data['meta'] = dict()
            # Add custom meta data
            response_data['meta'].update(meta_dict)
            # Call super to render the response
            response = super(CustomJSONRenderer, self).render(response_data, accepted_media_type, renderer_context)
        return response

父串行器和查看示例

class MovieListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Movie
        meta_dict = dict()
        meta_dict['foo'] = 'bar'

class MovieViewSet(generics.ListAPIView):
    queryset = Movie.objects.exclude(image__exact = "")
    serializer_class = MovieListSerializer
    permission_classes = (IsAdminOrReadOnly,)
    renderer_classes = (CustomJSONRenderer,)
    pagination_serializer_class = CustomPaginationSerializer
    paginate_by = 10

扫码关注云+社区