Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 766
Nate Parke Avatar asked Nov 18 '15 21:11

Nate Parke


3 Answers

You should set:

child=serializers.IntegerField(required=False)
like image 119
Linovia Avatar answered Oct 16 '22 19:10

Linovia


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.

like image 3
Arpit Goyal Avatar answered Oct 16 '22 19:10

Arpit Goyal


I would rather use

field = serializers.ListField(child=serializers.CharField(), allow_empty=True)
like image 3
Andriy Avatar answered Oct 16 '22 17:10

Andriy