Python Django rest-将字段转换为列表?
我的模型中有一个Textfield存储字典,如果可能的话,我想在rest序列化程序中将这个字段转换成字典 当字段返回字典但反斜杠所有引号时,是否可以将字符串转换为DICT的嵌套列表 谢谢 api目前返回的结果如下:Python Django rest-将字段转换为列表?,python,django,django-rest-framework,Python,Django,Django Rest Framework,我的模型中有一个Textfield存储字典,如果可能的话,我想在rest序列化程序中将这个字段转换成字典 当字段返回字典但反斜杠所有引号时,是否可以将字符串转换为DICT的嵌套列表 谢谢 api目前返回的结果如下: { "id": 3, "hostname": "WAN-EDGE", "timestamp": "2019-04-12T11:34:36.654521", "routing_table": "[{\"route\": \
{
"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\"},...]"
},...
}
期望的结果是一个嵌套的dict列表
{
"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
您也可以尝试使用as
导入json
类RoutingTableSerializer(serializers.ModelSerializer):
hostname=serializers.ReadOnlyField(source='device.hostname',)
rt=serializers.SerializerMethodField(source='routing\u table',read\u only=True)
def get_路由_表(自身,实例):
返回json.loads(instance.routing_表)
类元:
模型=设备数据
fields=('id','hostname','timestamp','rt')
我尝试了这个方法,但它仍然输出相同的rt=serializers.JSONField(source='routing\u table')我添加了我当前的serializerI假设get\u routing\u table应该是从一个错误中获取的,现在我在/api/rt_status/Expecting value处得到了JSONDecodeError:第1行第1列(char 0)您确定您有一个有效的JSON吗?(我试过并成功了)啊,有些字段中没有数据,所以我添加了一个尝试,除了json加载,现在它可以工作了,谢谢!为什么不在模型中使用JSONField而不是TextField呢?
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')