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.
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.
it validates your serializer with the condition of respective field specified in your serializer MessageSerializer .
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 .
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',
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With