Django rest-将字段转换为列表?

时间:2019-04-23 11:40:46

标签: python django django-rest-framework

我的模型中有一个存储字典的Textfield,如果可能的话,我想在其余序列化器中将此字段转换成字典。

在该字段返回字典但所有引号都加反斜杠的那一刻,是否可以将字符串转换为字典的嵌套列表?

谢谢

api当前返回如下:

{
        "id": 3,
        "hostname": "WAN-EDGE",
        "timestamp": "2019-04-12T11:34:36.654521",
        "routing_table": "[{\"route\": \"0.0.0.0\", \"subnet_mask\": \"0.0.0.0\", \"next_hop\": \"172.16.66.193\"}, {\"route\": \"10.10.21.0\", \"subnet_mask\": \"255.255.255.0\", \"next_hop\": \"172.16.67.146\"}, {\"route\": \"10.22.0.0\", \"subnet_mask\": \"255.255.0.0\", \"next_hop\": \"172.18.1.5\"}, {\"route\": \"10.31.0.0\", \"subnet_mask\": \"255.255.0.0\", \"next_hop\": \"172.16.67.146\"},...]"
    },...
}   

所需结果为字典的嵌套列表

{
        "id": 3,
        "hostname": "WAN-EDGE",
        "timestamp": "2019-04-12T11:34:36.654521",
        "routing_table": [
                        {
                            "route": "0.0.0.0",
                            "subnet_mask": "0.0.0.0",
                            "next_hop": "172.16.66.193"
                        },
                        {
                            "route": "10.10.21.0",
                            "subnet_mask": "255.255.255.0",
                            "next_hop": "172.16.67.146"
                        },
                        {
                            "route": "10.22.0.0",
                            "subnet_mask": "255.255.0.0",
                            "next_hop": "172.18.1.5"
                        },
                        {
                            "route": "10.31.0.0",
                            "subnet_mask": "255.255.0.0",
                            "next_hop": "172.16.67.146"
                        },...
                    ]
    },...
}

当前的序列化器:

class RoutingTableSerializer(serializers.ModelSerializer):
    hostname = serializers.ReadOnlyField(
        source='device.hostname',
    )
    rt = serializers.JSONField(
        source='routing_table'
    )
    class Meta:
        model = DeviceData
        fields = ('id','hostname','timestamp','rt')   

1 个答案:

答案 0 :(得分:2)

您可能需要serializers.JSONField()


更新1
您也可以将SerializerMethodField()设置为

import json


class RoutingTableSerializer(serializers.ModelSerializer):
    hostname = serializers.ReadOnlyField(source='device.hostname', )
    rt = serializers.SerializerMethodField(source='routing_table', read_only=True)

    def get_routing_table(self, instance):
        return json.loads(instance.routing_table)

    class Meta:
        model = DeviceData
        fields = ('id', 'hostname', 'timestamp', 'rt')