Rajeesh
Rajeesh

Reputation: 123

ModelSerializer with data as list

I have a ModelSerializer class as follows which I want to accept a list of items or a single item (dictionary) as data. The documentation states that passing "many" as True will support my requirement.

class PointSerializer(serializers.ModelSerializer):
    class Meta:
        model = Point

     def __init__(self, *args, **kwargs):
         if "data" in kwargs:
             if isinstance(kwargs["data"]):
                 kwargs["many"] = True
         super(PointSerializer, self).__init__(*args, **kwargs)

Now, providing data dictionary as follows works:

p = PointSerializer(data={'x':10, 'y': 12})
p.is_valid() # True

But this, with a list of dictionaries, fails:

p = PointSerializer(data=[{'x':10, 'y':12}, {'x':12, 'y':12}])
p.is_valid() # False
p.errors() # {'non_field_errors': ['Invalid data. Expected a dictionary, but got a list.']}

UPDATE:

Thanks to the chosen answer, I've changed my code to the following and it works fine:

class PointSerializer(serializers.ModelSerializer):

    class Meta:
        model = Point

>>> ps = PointSerializer(data={'x':10, 'y':12})
>>> ps.is_valid()
... True
>>> ps = PointSerializer(data=[{'x':10, 'y':12}, {'x':12, 'y':12}], many=True)
>>> ps.is_valid()
... True

Upvotes: 2

Views: 3961

Answers (1)

Linovia
Linovia

Reputation: 20976

many=True argument will only work when instantiating the serializer because it'll return a ListSerializer behind the scene.

Your option are either you set the many=True as serializer argument during creation call, either use explicitly the ListSerializer.

Upvotes: 1

Related Questions