AlexW
AlexW

Reputation: 2587

Django rest - convert field into a list?

I have a Textfield in my model which stores dictionaries, I would like to convert this field into a dictionary if possible in a rest serializer.

at the moment the field returns the dictionary but backslashes all the quotes, it is possible to convert the strings into a nested list of dicts?

Thanks

api currently returns below:

{
        "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\"},...]"
    },...
}   

desired result a nested list of dicts

{
        "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"
                        },...
                    ]
    },...
}

Current serialiser:

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')   

Upvotes: 1

Views: 234

Answers (1)

JPG
JPG

Reputation: 88569

You may need serializers.JSONField()


Update-1
You could also try with SerializerMethodField() as

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')

Upvotes: 2

Related Questions