chibisov / drf-extensions

DRF-extensions is a collection of custom extensions for Django REST Framework
http://chibisov.github.io/drf-extensions/docs
MIT License
1.48k stars 208 forks source link

UniqueFieldsMixin should not validate field when `required=False` #302

Closed elonzh closed 3 years ago

elonzh commented 3 years ago

Sometimes we have unique fields in Model with null=True, UniqueFieldsMixin shouldn't validate these fields when the data is not provided.

Currently KeyError will be raised when unique field value is not provided.

drf_writable_nested.mixins.UniqueFieldsMixin._validate_unique_fields:

    def _validate_unique_fields(self, validated_data):
        for field_name in self._unique_fields:
            if self.partial and field_name not in validated_data:
                continue
            unique_validator = UniqueValidator(self.Meta.model.objects.all())
            try:
                # KeyError will raise when unique field is not required.

                # `set_context` removed on DRF >= 3.11, pass in via __call__ instead
                if hasattr(unique_validator, 'set_context'):
                    unique_validator.set_context(self.fields[field_name])
                    unique_validator(validated_data[field_name])
                else:
                    unique_validator(validated_data[field_name], self.fields[field_name])
            except ValidationError as exc:
                raise ValidationError({field_name: exc.detail})
elonzh commented 3 years ago

sorry this is a issue for drf-writable-nested