如何将键值添加到ModelSerilzer响应中

时间:2015-09-28 14:13:54

标签: django-rest-framework

使用模型

class PlanSerializer(serializers.ModelSerializer):

    class Meta:
        model = Plan
        fields = ("id", "name", "amount")

使用ListAPIView(因为只有/ GET /操作在此资源上有效)

class PlanList(generics.ListAPIView):
    queryset = Plan.objects.all()
    serializer_class = PlanSerializer

/ GET /

  [
        {
            "id": 4, 
            "name": "free", 
            "amount": 110.0
        }, 
        {
            "id": 3, 
            "name": "permium", 
            "amount": 60.0
        }
    ]

在响应中有一个常量值DISCOUNT,它应该只在响应中出现一次,因此响应看起来像

  [
        {
            "id": 4, 
            "name": "free", 
            "amount": 110.0
        }, 
        {
            "id": 3, 
            "name": "permium", 
            "amount": 60.0
        },
       {"DISCOUNT": 210}
    ]

我尝试将此折扣作为属性并在序列化程序中使用它 但是每个实例都重复这个,我希望它只出现一次。

对此有何想法?

2 个答案:

答案 0 :(得分:0)

您可以从list method覆盖ListAPIView。将CONSTANT附加到最终的序列化数据。

class PlanList(generics.ListAPIView):
    queryset = Plan.objects.all()
    serializer_class = PlanSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        #add your constant here
        final_response = serializer._data.copy()
        final_response["DISCOUNT"] = 210
        return Response(final_response)

答案 1 :(得分:0)

要向ModelSerializer回复添加另一个字典,您可以覆盖list()视图的PlanList方法。

class PlanList(generics.ListAPIView):
    queryset = Plan.objects.all()
    serializer_class = PlanSerializer

    def list(self, request, *args, **kwargs):
        instance = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(instance)
        if page is not None:
            serializer = self.get_pagination_serializer(page)
        else:
            serializer = self.get_serializer(instance, many=True)

        serializer_data = serializer.data # get the default serialized data 
        serializer_data.append({"DISCOUNT": 210}) # add a custom dictionary in the response
        return Response(serializer_data) 

然后,您的回答将类似于:

 [
        {
            "id": 4, 
            "name": "free", 
            "amount": 110.0
        }, 
        {
            "id": 3, 
            "name": "permium", 
            "amount": 60.0
        },
       {
            "DISCOUNT": 210
       }
    ]