Nate Parke
Nate Parke

Reputation: 291

Allow empty list in serializers.ListField

I am using Django REST framework 3.3 and am trying to serialize a list that could be empty with the provided serializers.ListField class that is included in the framework. My current instantiation of the field looks like this

 countrypreferences = serializers.ListField(child=serializers.IntegerField(),
                                            source='country_preference_ids',
                                            allow_null=True)

When testing the API I always seem to get a 400 response if I let the field be an empty list. It would seem like this kind of functionality would be pretty common but I can't find a way to allow the empty list. Thanks!

Upvotes: 14

Views: 10512

Answers (3)

Andriy
Andriy

Reputation: 1628

I would rather use

field = serializers.ListField(child=serializers.CharField(), allow_empty=True)

Upvotes: 7

Arpit Goyal
Arpit Goyal

Reputation: 2254

In addition to that you can also provide a default value to the ListField in the serializers

field = serializers.ListField(default = [])

This will set the field as an empty list if u send None or no value.

Upvotes: 4

Linovia
Linovia

Reputation: 21006

You should set:

child=serializers.IntegerField(required=False)

Upvotes: 12

Related Questions