简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM