Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UniqueFieldsMixin should not validate field when required=False #133

Open
elonzh opened this issue Jan 7, 2021 · 0 comments
Open

UniqueFieldsMixin should not validate field when required=False #133

elonzh opened this issue Jan 7, 2021 · 0 comments

Comments

@elonzh
Copy link

elonzh commented Jan 7, 2021

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})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant