Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get pretty output from rest_framework serializer

I'm using the django rest_gramework serializer, to dump json of my objects:

response = InstallSerializer(Install.objects.all(), many=True).data
return StreamingHttpResponse(response, content_type='application/json')

where

class InstallSerializer(serializers.ModelSerializer):
    modules = ModuleSerializer(many=True)

    class Meta:
        model = Install
        fields = ('id', 'install_name', 'modules')

etc.

However, this output is not "readable" ... it comes all on one line.

{'id': 1, 'install_name': u'Combat Mission Battle For Normandy', 'modules': [{'id': 1, 'name': u'Combat Mission Battle For Normandy', 'versions': [{'id': 1, 'name': u'1.00-Mac', 'brzs': [1, 2, 3]}]}]}

Is there a way to askk the serializer to format the output better?

(For visual inspection for debug)

Note: I just learned that my approach for outputting the serialized form shown above does not even produce valid json, though it looks similar. You have to do the json.dump step shown in the accepted answer below to get valid json, and as a bonus it is pretty as well.

like image 579
GreenAsJade Avatar asked Apr 21 '14 10:04

GreenAsJade


People also ask

What does serializer data return?

The BaseSerializer class caches its data attribute on the object, but Serializer. data returns a copy of BaseSerializer. data every time it is accessed (via ReturnDict ). This is a little inefficient (which is not a big deal), but it means that any changes to the data dict will essentially be reset when Serializer.

What does serializer Is_valid do?

it validates your serializer with the condition of respective field specified in your serializer MessageSerializer .

What is difference between ModelSerializer and serializer?

The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model. It will automatically generate validators for the serializer, such as unique_together validators. It includes simple default implementations of .


1 Answers

I did this with:

class PrettyJsonRenderer(JSONRenderer):    
    def get_indent(self, accepted_media_type, renderer_context):
        return 2

And then specify PrettyJsonRenderer in your site's settings.py file:

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'myapp.util.PrettyJsonRenderer',
    )
}
like image 193
mpenkov Avatar answered Sep 21 '22 18:09

mpenkov