在Serializer中自定义嵌套数据

时间:2018-01-11 03:22:15

标签: python django django-rest-framework

我有一个ModelSerializer:

class WorkOrderRetrieveSerializer(ModelSerializer):

    workordercomments = WorkOrderCommentForWorkOrderSerializer(many=True, read_only=True)
    class Meta:
        model = WorkOrder
        fields = "__all__"

JSON数据如下:

{
    "id": 1,
    "workordercomments": [
    .....

        {
            "id": 21,
            "content": "test files",
            "files": "[71]",
            "ctime": "2018-01-11T11:03:17.874268+08:00",
            "uptime": "2018-01-11T11:03:17.874362+08:00",
            "workorder": 1,
            "comment_user": {
                "id": 5,
                "username": "test03",
                "is_admin": true
            }
        }
    ],
    "workorder_num": "WON15118747168252",
    "name": "order01",
    "content": "first conntetn",
    "workordertype": "teck",
    "workorder_status": "created",
    "user_most_use_email": "lxas@128.com",
    "server_id": null,
    "public_ip": null,
    "belong_area": null,
    "files": null,
    "ctime": "2017-11-28T21:11:56.826971+08:00",
    "uptime": "2017-11-28T21:11:56.827064+08:00",
    "to_group": 3,
    "user": 2
}

我的JSON中的"files": "[71]",是一个包含文件id的组的字符串。

workordercomments是工单的相关名称。

我想在JSON workordercomments中显示files,如下所示:

        {
            "id": 21,
            "content": "test files",
            "files": "['/media/images/xxxxx.png']",
            "ctime": "2018-01-11T11:03:17.874268+08:00",
            "uptime": "2018-01-11T11:03:17.874362+08:00",
            "workorder": 1,
            "comment_user": {
                "id": 5,
                "username": "test03",
                "is_admin": true
            }
        }

"文件"我想要的是链接而不是id

"files": "['/media/images/xxxxx.png']", 

"files": ['/media/images/xxxxx.png'],

是否可以自定义格式?我应该在串行器中实现什么功能?

1 个答案:

答案 0 :(得分:0)

您需要根据文档实现自定义序列号,并覆盖ModelSerializer生成的默认值。

例如:

from rest_framework.fields import Field

class FileRelatedField(RelatedField):
    def to_representation(self, instance):
        return instance.file_path # or whereever that path comes from


class WorkOrderRetrieveSerializer(ModelSerializer):
    class Meta:
        model = WorkOrder
        fields = '__all__'

    files = FileRelatedField(
        many=True, 
        source='file_set.all'
    )

根据您的__str__值在文件模型上的显示方式,您可以执行以下操作:

from rest_framework.serializers import StringRelatedField

class WorkOrderRetrieveSerializer(ModelSerializer):
    class Meta:
        model = WorkOrder
        fields = '__all__'

    files = StringRelatedField(
        many=True, 
        source='file_set.all'
    )