gpt4 book ai didi

json - 如何从rest_framework序列化器获得漂亮的输出

转载 作者:行者123 更新时间:2023-12-04 01:29:12 25 4
gpt4 key购买 nike

我正在使用 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,作为奖励,它也很漂亮。

最佳答案

我这样做了:

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

然后指定 PrettyJsonRenderer在您网站的 settings.py文件:
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'myapp.util.PrettyJsonRenderer',
)
}

关于json - 如何从rest_framework序列化器获得漂亮的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23195210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com