【发布时间】:2014-06-05 09:19:39
【问题描述】:
我正在使用 django rest_gramework 序列化程序来转储我的对象的 json:
response = InstallSerializer(Install.objects.all(), many=True).data
return StreamingHttpResponse(response, content_type='application/json')
在哪里
class InstallSerializer(serializers.ModelSerializer):
modules = ModuleSerializer(many=True)
class Meta:
model = Install
fields = ('id', 'install_name', 'modules')
等等
但是,这个输出不是“可读的”......它全部在一行中。
{'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]}]}]}
有没有办法让序列化器更好地格式化输出?
(用于调试的目视检查)
注意:我刚刚了解到,我输出上面显示的序列化表单的方法甚至不会产生有效的 json,尽管它看起来很相似。您必须执行下面接受的答案中显示的 json.dump 步骤才能获得有效的 json,而且它也很漂亮。
【问题讨论】:
-
您始终可以使用 Browsable API django-rest-framework.org/topics/browsable-api#urls 进行调试。它以可读格式打印 JSON。
标签: json django serialization django-rest-framework