32

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?

Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237
Alan Sergeant
  • 1,516
  • 1
  • 13
  • 10
  • 3
    What is the relevant output of `repr(SerializerA())`? You probably want to set `allow_null` for `DetailsSerializer`. – Kevin Brown-Silva Apr 13 '15 at 15:44
  • Hi, the output is `SerializerA(): details = DetailsSerializer(required=False): a = CharField(max_length=100, min_length=1, required=True)` – Alan Sergeant Apr 14 '15 at 06:30
  • 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 Apr 14 '15 at 06:33

1 Answers1

68

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.

Alan Sergeant
  • 1,516
  • 1
  • 13
  • 10
  • Man I'm struggling with this error for a couple of hours. Thanks! By the way, where can I find this serializer docs? – Joabe Lucena Nov 18 '19 at 17:24
  • If you have a 1:N relation, setting required=False is not enough. You have to pass many=true to the serializer. ``` class CustomerSerializer(serializers.ModelSerializer): contact = ContactSerializer(many=True, read_only=True) ``` Got here through Google, so I hope, someone will read this comment – Ondřej Kolín May 08 '20 at 12:26