Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override JSONSerializer on django rest framework

I'm trying to apply this fix on my django rest framework Adding root element to json response (django-rest-framework)

But I'm not sure how to override the json serializer on django rest framework, any help would be great.

The end result would be to have the root node name on the Json, because right now it's just an array of objects without the root name i.e.

not it looks like this

[{"foo":"bar"}]

I would need it to be like this

{"element": [{"foo":"bar"}]}

to get it to work with Ember JS

Thanks

like image 877
ShinySides Avatar asked Dec 06 '13 12:12

ShinySides


People also ask

How do you pass extra context data to Serializers in Django REST Framework?

In function-based views, we can pass extra context to serializer with “context” parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with “self. context”. From example, to get “exclude_email_list” we just used code 'exclude_email_list = self.

Why do we need Serializers in Django REST Framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.


1 Answers

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, )
    # ...
like image 178
mariodev Avatar answered Oct 12 '22 12:10

mariodev