如何将Django REST Framework JSON响应的一部分从列表更改为字典?

时间:2017-11-18 19:14:16

标签: python json django django-rest-framework

更具体地说,我需要将我的响应的嵌套部分作为多项目字典而不是许多单项字典的列表。

我正在返回我想要的所有数据,但我无法弄清楚如何在没有我认为无关的列表的情况下更明智地格式化它

以下是我目前获得的(简化)回复:

{
    "uielements": [
        {
            "home-bg": {
                "label_text_color": "#123456",
                "tag_display_text": "young"
            }    
        },
        {
            "home-speak-btn": {
                "label_text_color": "",
                "tag_display_text": null
            }
        }
    ]
}

我希望回复采用这种格式:

{
    "uielements": {
        "home-bg": {
            "label_text_color": "#123456",
            "tag_display_text": "young"
        },   
        "home-speak-btn": {
            "label_text_color": "",
            "tag_display_text": null
        }
    }
}

以下是我的相关serializer.py代码:

class UIElementProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = UIElement

    def to_representation(self, obj):
        result = super(UIElementProjectSerializer, self).to_representation(obj)
        uien = UIElementName.objects.filter(id=result['uielementname'])[0]
        return {uien.name: result}

以及我的相关views.py代码:

class ProjectViewSet(viewsets.ViewSet):

...

    @detail_route(methods=['get'])
    def uielements(self, request, pk=None):
        uielements = UIElementFilterSet(params)
        serializer = serializers.UIElementProjectSerializer(uielements, many=True)
        return Response({"uielements": serializer.data})

2 个答案:

答案 0 :(得分:1)

原来我需要做的是使用Dmitry Kovriga提供的代码而不是新的自定义ListSerializer,而是在序列化发生后的视图中。

更新 views.py

class ProjectViewSet(viewsets.ViewSet):
    ...

    @detail_route(methods=['get'])
    def uielements(self, request, pk=None):
        uielements = UIElementFilterSet(params)
        serializer = serializers.UIElementProjectSerializer(uielements, many=True)
        result = {}
        for element in serializer.data:
            for key, value in element.items():
                result[key] = value
        return Response({"uielements": result})

答案 1 :(得分:0)

您可以为UIElementProjectSerializer编写自定义ListSerializer并覆盖它的to_representation方法

class UIElementProjectListSerializer(serializers.ListSerializer):

    def to_representation(self, data):
        result = {}
        for element in super(UIElementProjectListSerializer, self).to_representation():
            for key, value in element.items():
                result[key] = value
        return result

class UIElementProjectSerializer(serializers.ModelSerializer):
    class Meta:
        list_serializer_class = UIElementProjectListSerializer
        ...