栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

对于后代,以下是最终解决方案。由于它现在也重新设置了分页结果的格式,因此与原始版本相比略有增长。

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

serializer:

from rest_framework.serializers import ModelSerializerfrom api.models import Contactclass 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')

renderer:

from rest_framework.renderers import JSonRendererclass 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

pagination:

from rest_framework import pagination, serializersclass 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'


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/420426.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号