[Answered ]-Rest framework how to create optional nested object?

0👍

✅

When i from DRF 3.1.3 upgraded to DRF 3.2.2,I don’t know what was going on,it just works 🙁

It pass through .is_valid() to reach the .create().

2👍

Both rich and simple posts are required in your serializer. You should make them optional. If you need at least one of them to be required, you can do that in validate():

class PostSerializer(serializers.ModelSerializer):
    simple = SimplePostSerializer(required=False)
    rich = RichPostSerializer(required=False)
    ...
    def validate(self, data):
        data = super(PostSerializer, self).validate(data)
        if not any([data.get('simple'), data.get('rich')]):
            raise serializers.ValidationError('Either simple or rich is required')
        return data

Leave a comment