27
votes

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?

1
What is the relevant output of repr(SerializerA())? You probably want to set allow_null for DetailsSerializer.Kevin Brown
Hi, the output is SerializerA(): details = DetailsSerializer(required=False): a = CharField(max_length=100, min_length=1, required=True)Alan Sergeant
Also, according to the docs, If a nested representation may optionally accept the None value you should pass the required=False flag to the nested serializer. To me this means I don't require the allow_null param?Alan Sergeant

1 Answers

62
votes

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.