diff options
| author | Tom Christie | 2014-11-10 12:32:03 +0000 | 
|---|---|---|
| committer | Tom Christie | 2014-11-10 12:32:03 +0000 | 
| commit | fd7db776addbd5e30f132fe6846ec5c5caab5c40 (patch) | |
| tree | 27d46462bca33a82152125ac1d12c23223d64dc4 /rest_framework/validators.py | |
| parent | 8c1fa0b87d9c195420dd7a24c3bdf1b7d3295f1b (diff) | |
| download | django-rest-framework-fd7db776addbd5e30f132fe6846ec5c5caab5c40.tar.bz2 | |
Bring UniqueValidator implementation in line with other uniquness validators.
Diffstat (limited to 'rest_framework/validators.py')
| -rw-r--r-- | rest_framework/validators.py | 22 | 
1 files changed, 18 insertions, 4 deletions
| diff --git a/rest_framework/validators.py b/rest_framework/validators.py index d7f847aa..fa4f1847 100644 --- a/rest_framework/validators.py +++ b/rest_framework/validators.py @@ -35,12 +35,26 @@ class UniqueValidator:          # Determine the existing instance, if this is an update operation.          self.instance = getattr(serializer_field.parent, 'instance', None) -    def __call__(self, value): -        # Ensure uniqueness. +    def filter_queryset(self, value, queryset): +        """ +        Filter the queryset to all instances matching the given attribute. +        """          filter_kwargs = {self.field_name: value} -        queryset = self.queryset.filter(**filter_kwargs) +        return queryset.filter(**filter_kwargs) + +    def exclude_current_instance(self, queryset): +        """ +        If an instance is being updated, then do not include +        that instance itself as a uniqueness conflict. +        """          if self.instance is not None: -            queryset = queryset.exclude(pk=self.instance.pk) +            return queryset.exclude(pk=self.instance.pk) +        return queryset + +    def __call__(self, value): +        queryset = self.queryset +        queryset = self.filter_queryset(value, queryset) +        queryset = self.exclude_current_instance(queryset)          if queryset.exists():              raise ValidationError(self.message) | 
