覆盖Django rest框架上的JSONSerializer

xzabzqsa  于 2022-11-19  发布在  Go
关注(0)|答案(2)|浏览(134)

我正在尝试在我的django rest框架Adding root element to json response (django-rest-framework)上应用这个修复
但是我不知道如何在djangorest框架上覆盖json序列化器,任何帮助都是很好的。
最终结果是在Json上有根节点名称,因为现在它只是一个没有根名称的对象数组,即
没有看起来像这样
[{“foo”:“bar”}]
我需要这样
{“元素”:[{“foo”:“bar”}]}
让它和Ember JS一起工作
谢谢

dddzy1tm

dddzy1tm1#

我想你在你给的帖子里有你的答案。
您需要定义自定义JSON渲染器

from rest_framework.renderers import JSONRenderer

class EmberJSONRenderer(JSONRenderer):

    def render(self, data, accepted_media_type=None, renderer_context=None):
        data = {'element': data}
        return super(EmberJSONRenderer, self).render(data, accepted_media_type, renderer_context)

并将其用作设置中的默认渲染器,或用作为视图显式定义的渲染器,如:

class MyView(APIView):
    renderer_classes = (EmberJSONRenderer, )
    # ...
fcg9iug3

fcg9iug32#

def finalize_response(self, request, response, *args, **kwargs):
    response_code = response.status_code
    resp = Response(data=response.data, status=response_code)
    resp.accepted_renderer=request.accepted_renderer
    resp.accepted_media_type = request.accepted_media_type
    resp.renderer_context = self.get_renderer_context()
    return resp
 def get_renderer_context(self):
    """
    Returns a dict that is passed through to Renderer.render(),
    as the `renderer_context` keyword argument.
    """
    # Note: Additionally 'response' will also be added to the context,
    #       by the Response object.
    return {
        'view': self,
        'args': getattr(self, 'args', ()),
        'kwargs': getattr(self, 'kwargs', {}),
        'request': getattr(self, 'request', None)
    }

相关问题