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})
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: