在Django中自定义序列化对象

时间:2018-12-04 09:56:45

标签: django django-rest-framework

我对api有响应

 "mailinglist": [
        {
            "id": 690,
            "name": "Donotdelete",
            "count": "3",
            "mailing_list": 109,
            "person": [
                {
                    "id": 939,
                    "first_name": "Aladdin",
                    "last_name": "Abdul",
                    "email": "aladdin@sharklasers.com",
                    "mailinglist_id": 109
                }
            ]
        },
        {
            "id": 691,
            "name": "Donotdelete",
            "count": "3",
            "mailing_list": 109,
            "person": [
                {
                    "id": 938,
                    "first_name": "smitha",
                    "last_name": "sraj",
                    "email": "smithasraj.kp@gmail.com",
                    "mailinglist_id": 109
                }
            ]
        }
    ]

使用嵌套的序列化器方法。但是我必须将此响应更改为

"mailinglist": [
        {
            "id": 690,
            "name": "Donotdelete",
            "count": "3",
            "mailing_list": 109,
            "person": [
                {
                    "id": 938,
                "first_name": "smitha",
                "last_name": "sraj",
                "email": "smithasraj.kp@gmail.com",
                "mailinglist_id": 109
                },{
                    "id": 939,
                    "first_name": "smitha",
                    "last_name": "sraj",
                    "email": "smithasraj.kp@gmail.com",
                    "mailinglist_id": 109
                }
            ]
        }
    ]

名称计数邮件列表等常见字段应位于数组之外,是否可以选择执行此操作?我们可以迭代序列化器数据对象并可以对其进行自定义吗?

1 个答案:

答案 0 :(得分:0)

是的,您可以覆盖每个序列化器的to_representation()方法。

每个序列化器都有一个to_representation(),它将创建json数据以进行响应。您可以在其中添加所需的任何项目,也可以弹出不在正确位置的任何项目。例如:

class TestSerializer(serializers.Serializer):

     def to_representation(self, instance):
         r = super().to_representation(instance)
         r.update({'test': 'value of test'}
         return r