Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

python - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, )
    # ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...