如何为ModelSerilzer响应添加键值 [英] How to add key value to ModelSerilzer response

查看:58
本文介绍了如何为ModelSerilzer响应添加键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用模型

class PlanSerializer(serializers.ModelSerializer):

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

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

using ListAPIView (since only /GET/ operation is valid on this resource)

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 应当在响应中只出现一次,因此响应看起来像

there is a constant value DISCOUNT to be send in the response which should appear only once in the response , so that response looks like

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

我试图做到这一点打折作为一种属性,并在序列化器
中使用它,但是这种情况在每个实例中都在重复,我希望它只出现一次。

I tried to make the this discount as a property and using it in serializer but this was getting repeated for each instance, I want it to appear just once.

对此有何想法?

推荐答案

要将其他词典添加到 ModelSerializer 响应中,您可以覆盖 PlanList 视图的 list()方法。

To add another dictionary to the ModelSerializer response, you can override the list() method of the PlanList view.

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) 

然后,您的响应将类似于:

Then, you response will look something like:

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

这篇关于如何为ModelSerilzer响应添加键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆