Django

Modify object data by write Custom Renderer in Django Rest Framework

29 Mar , 2015  

When we need to modify object or results from DRF / Django Rest Framework, all we need just write a custom JSON Renderer like below :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class JGridJSONRenderer(renderers.JSONRenderer):
    def render(self, data, accepted_media_type=None, renderer_context=None):
        new_rows = []

        # Name the object list
        for obj in data['rows']:
            obj = dict(obj)
            new_rows.append({'id': obj['id'], 'cell': obj})

        data['rows'] = new_rows
        response_data = data
        response = super(JGridJSONRenderer, self).render(response_data, accepted_media_type, renderer_context)

        return response