Jekson
Jekson

Reputation: 3262

Right way to convert serializer data to python dict

I'm looking for a way to get the dictionary from the serialized data. I'm using that method now.

m = Mymodel.objects.all()
serializer = RfiParticipationCsvDownloadSerializer(m)
print(type(serializer)) # <class'apps.vendors.serializers.RfiParticipationCsvDownloadSerializer'>
qs = json.dumps(serializer.data)
print(type(qs)) # <class 'str'>
module_dict = json.loads(qs)
print(type(module_dict)) #<class 'dict'>

But I don't think it's the best or the right one. Tell me the best solution.

Upvotes: 1

Views: 5215

Answers (2)

tomo.hirano
tomo.hirano

Reputation: 71

serializer.data is ReturnList. ReturnList is a list of OrderedDict and we can cast OrderedDict to dict. So the code would be like:

    all_objects = MyModel.objects.all()
    serializer = MyModelSerializer(all_objects, many=True)
    serializer_return_list = serializer.data

    converted_data = []
    for ordered_dict in serializer_return_list:
        converted_data.append(dict(ordered_dict))

    print(json.dumps(converted_data))

Upvotes: 1

Tymofii Tsiapa
Tymofii Tsiapa

Reputation: 101

serializer.data already has a ReturnDict type, so you can work with it like with a dict or you can copy serializer.data to a new dict if you need to change data because serializer.data is a property of the class and it is unmutable.

Upvotes: 5

Related Questions