Skip to content

inconsistent validation behavior for child serializers #7369

@ozgurakcali

Description

@ozgurakcali

Steps to reproduce

With the following serializers structure:


class ChildSerializer(serializers.ModelSerializer):
    field_1 = serializers.CharField(required=True)
    field_2 = serializers.CharField(required=True)
    
    def validate(self, attrs):
        if attrs.get('field_2') == 'invalid':
            raise serializers.ValidationError()
        return attrs

class ParentSerializer(serializers.ModelSerializer):
    children = ChildSerializer(many=True, read_only=False)

serializer = ParentSerializer(data={
    'children': [{
            'field_2': 'value'
    }]
})
serializer.is_valid(raise_exception=True) # No validation error raised in this case, even though field_1 is missing in data

serializer = ParentSerializer(data={
    'children': [{
            'field'_1': 'value',
            'field'_2': 'invalid',
    }]
})
serializer.is_valid(raise_exception=True) # Validation error raised in this case, as field_2 value is 'invalid', that makes the condition on **validate** method hold

Expected behavior

Without explicitly calling is_valid method of child serializer from parent serializer, either do not run any validations on child serializer, or run all validations on child serializer.

Actual behavior

When is_valid method is run on parent serializer, if we do not run child serializer's is_valid method explicitly (in validate_children method for example), validations for field_1 being required are not checked, but validate method of ChildSerializer is called.

If we explicitly call is_valid method of ChildSerializer, all validations for ChildSerializer are run.

As they are defined now, serializer is actually invalid for both cases, but a validation error is raised for the second case, but not for the first case.

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