Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework Nested Serializer required=False error

In DRF v3.1, I have a nested serializer much like the one detailed in the docs - http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects

class SerializerA(serializers.Serializer):
    details = DetailsSerializer(required=False)

However, when trying to use this serializer and not supplying the details, I receive the following:

{u'details': [u'This field may not be null.']}

This seems incorrect given the docs?

Has anyone else come across this or can verify this as a bug?

like image 405
Alan Sergeant Avatar asked Apr 13 '15 13:04

Alan Sergeant


1 Answers

Ok, so Kevin Browns comment is correct. I needed to add allow_null=True.

class SerializerA(serializers.Serializer):
    details = DetailsSerializer(required=False, allow_null=True)

The reason for this is that having required=False allows the field details to be absent from the data when constructing the serializer.

e.g. s = SerializerA(data={})

whereas allow_null permits the the param to be specified but be null.

e.g. s = SerializerA(data={'details': None})

This opens up another issue with DRF Browsable API, but i'll ask that in a different question.

like image 175
Alan Sergeant Avatar answered Oct 20 '22 01:10

Alan Sergeant