Search code examples
pythondjangodjango-rest-frameworkdjango-serializer

DRF - serializer for list of dictionaries


I've a serializer class which return "single" data well, like:

class MySerializer(serializers.Serializer):
    num: Decimal = serializers.DecimalField(max_digits=10, decimal_places=4, required=True
    uid: str = serializers.CharField(max_length=30, required=True)

.

I'd like to add a parameter (other) to this serializer which would return list of dictionaries, but I can't find out how to do it.

The structure of other would look like this:

[
    {'p1': int,
    'p2': int,
     'p3': {another dict which has already a serializer class}
    }
]

What would be the way to achieve this?

If I add serializers.DictField or serializers.ListField I always got back "'list' object has no attribute 'items' AttributeError" or "Object of type PoCo is not JSON serializable TypeError" where PoCo is a class of mine.


Solution

  • Use serializers.SerializerMethodField.

    class MySerializer(serializers.Serializer):
        num: Decimal = serializers.DecimalField(max_digits=10, decimal_places=4, required=True
        uid: str = serializers.CharField(max_length=30, required=True)
        other = serializers.SerializerMethodField("get_other_filed)
    
        def get_other_field(self,obj):
            result = {} # Your dict
            return result