31

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?

3
  • 3
    What is the relevant output of repr(SerializerA())? You probably want to set allow_null for DetailsSerializer. Commented Apr 13, 2015 at 15:44
  • Hi, the output is SerializerA(): details = DetailsSerializer(required=False): a = CharField(max_length=100, min_length=1, required=True) Commented Apr 14, 2015 at 6: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? Commented Apr 14, 2015 at 6:33

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Man I'm struggling with this error for a couple of hours. Thanks! By the way, where can I find this serializer docs?
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.