django - 将根元素添加到 json 响应 (django-rest-framework)

标签 django django-rest-framework

我正在尝试确定使用 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

现在棘手的部分是根据调用 render() 的 View 动态设置 root_element

任何指示/建议将不胜感激,

干杯

最佳答案

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

此外,我之前应该已经指出,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'

关于django - 将根元素添加到 json 响应 (django-rest-framework),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14824807/

相关文章:

django - 如何测试从 OSX 上的 Web 应用程序发送电子邮件?

django - Django 的 QuerySets 是否足够懒惰来处理大数据集?

python - Django 休息框架 : @detail_route and @list_route with same name

python - 如何发送 Elasticsearch 查询结果的响应API?

python - 将 GET 参数转换为 Django REST Framework 中 Request 对象上的 POST 数据

javascript - 从 MySQL 加载数据以在 D3 中用于创建折线图

Django:动态数据库文件

django - 守护进程 celery 进程 celeryd-multi 未找到

Django Rest Framework - 如何获取外键的外键字段

python - Django REST教程DEBUG=FALSE报错