Skip to content

Django-polymorphic does not update the PolymorphicSerializer's validated_data after running the child's validation method #378

@johnmatthewtennant

Description

@johnmatthewtennant

I override the self.validate() method in a polymorphic model. In that method, I make some changes to validated data, namely adding the user.

validated_data['user'] = self.context['request'].user

I noticed this change wasn't being reflected in the created object.
This is because the PolymorphicSerializer does not update its _validated_data after running the child's validate method.

The problematic code is in the "is_valid" method. See my three commented lines at the bottom that could help.

    def is_valid(self, *args, **kwargs):
        valid = super(PolymorphicSerializer, self).is_valid(*args, **kwargs)
        try:
            resource_type = self._get_resource_type_from_mapping(self.validated_data)
            serializer = self._get_serializer_from_resource_type(resource_type)
        except serializers.ValidationError:
            child_valid = False
        else:
            child_valid = serializer.is_valid(*args, **kwargs)
            # resource_type = self._validated_data[self.resource_type_field_name]
            # self._validated_data = serializer._validated_data
            # self._validated_data[self.resource_type_field_name] = resource_type
            self._errors.update(serializer.errors)
        return valid and child_valid 

My workaround has been to override the perform_create() method on the ViewSet as follows:

    def perform_create(self, serializer):
        child_resource_type = serializer.validated_data[serializer.resource_type_field_name]
        child_serializer = serializer._get_serializer_from_resource_type(child_resource_type)
        serializer.instance = child_serializer.save()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions