[Solved]-Override JSONSerializer on django rest framework

23๐Ÿ‘

โœ…

I think you have your answer there in the post youโ€™ve given.

You need to define custom JSON renderer

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)

and use it as default renderer either in settings or as an explicitly defined render for you view, like:

class MyView(APIView):
    renderer_classes = (EmberJSONRenderer, )
    # ...
๐Ÿ‘คmariodev

0๐Ÿ‘

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)
    }
๐Ÿ‘คsaif alikhan

Leave a comment