Django / rest显示嵌套对象

时间:2016-06-27 10:39:59

标签: django django-rest-framework

我的用户序列化程序:

class UserDetailsSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserModel
        fields = ('username', 'email', 'first_name', 'last_name')
        read_only_fields = ('email', )

当前回复:

{
    "username": "django",
    "email": "email@gmail.com",
    "first_name": "bim",
    "last_name": "bem"
}

我想让它以“user”作为键嵌套响应,如下所示:

{user:
    {
    "username": "django",
    "email": "email@gmail.com",
    "first_name": "bim",
    "last_name": "bem"
    }
}

1 个答案:

答案 0 :(得分:0)

为此,您可以从序列化程序返回的字典创建自己的字典并提供它。

这样的事情:

serializer = UserDetailsSerializer(somedata)
serialized_data = serializer.data
jsondata = JSONRenderer().render({'user': serialized_data })