Have rest framework return null when response is None

时间:2016-08-23 15:33:13

标签: django-rest-framework

My understanding is that rest framework 3's

Response(None)

is exactly equivalent to

Response()

, where the (JSON) result is an empty response body, rather than null. An empty response would translate to a JavaScript undefined rather than null, which is incorrect. So, should I insist on null being returned, I cannot do:

Response('null')

because that is understandably serialised to "null". So, in order to yield an actual null in the response, I must hack up a custom renderer that indiscriminately returns a JSON dump of its data:

class PlainTextRenderer(renderers.BaseRenderer):
    media_type = 'application/json'
    format = 'json'

    def render(self, data, media_type=None, renderer_context=None):
        import json
        return json.dumps(data)

renderer_classes = (PlainTextRenderer,)

This seems too hacky to be true. Although the renderer does work, am I missing something much simpler?

0 个答案:

没有答案