How to serialize an 'object list' in Django REST Framework

后端 未结 3 751
一个人的身影
一个人的身影 2021-02-13 20:59

I need a serializer for something like this:

{
    \"items\": {
        12: {
            \"name\": \"item 1\"
        },
        66: {
            \"name\": \"i         


        
3条回答
  •  时光取名叫无心
    2021-02-13 21:18

    There is a ListField in django rest framework 3, you can check documentation here http://www.django-rest-framework.org/api-guide/fields/#listfield

    For your example you can do something like this:

    class ItemSerializer(serializers.Serializer):
        id = serializers.IntegerField()
        name = serializers.CharField()
    
    class ItemsSerializer(serializers.Serializer):
        items = serializers.ListField(child=ItemSerializer())
    

    The later serializer can be also:

    class ItemsSerializer(serializers.Serializer):
        items = ItemSerializer(many=True)
    

提交回复
热议问题