Case insensitive uniqueness validation (#4534)

This commit is contained in:
Rowan Seymour 2016-10-04 14:44:50 +02:00 committed by Tom Christie
parent 0b373be712
commit 883efbc19f
3 changed files with 6 additions and 4 deletions

View File

@ -61,6 +61,7 @@ It takes a single required argument, and an optional `messages` argument:
* `queryset` *required* - This is the queryset against which uniqueness should be enforced.
* `message` - The error message that should be used when validation fails.
* `lookup` - The lookup used to find an existing instance with the value being validated. Defaults to `'exact'`.
This validator should be applied to *serializer fields*, like so:

View File

@ -42,10 +42,11 @@ class UniqueValidator(object):
"""
message = _('This field must be unique.')
def __init__(self, queryset, message=None):
def __init__(self, queryset, message=None, lookup='exact'):
self.queryset = queryset
self.serializer_field = None
self.message = message or self.message
self.lookup = lookup
def set_context(self, serializer_field):
"""
@ -62,7 +63,7 @@ class UniqueValidator(object):
"""
Filter the queryset to all instances matching the given attribute.
"""
filter_kwargs = {self.field_name: value}
filter_kwargs = {'%s__%s' % (self.field_name, self.lookup): value}
return qs_filter(queryset, **filter_kwargs)
def exclude_current_instance(self, queryset):

View File

@ -31,7 +31,7 @@ class RelatedModel(models.Model):
class RelatedModelSerializer(serializers.ModelSerializer):
username = serializers.CharField(source='user.username',
validators=[UniqueValidator(queryset=UniquenessModel.objects.all())]) # NOQA
validators=[UniqueValidator(queryset=UniquenessModel.objects.all(), lookup='iexact')]) # NOQA
class Meta:
model = RelatedModel
@ -103,7 +103,7 @@ class TestUniquenessValidation(TestCase):
AnotherUniquenessModel._meta.get_field('code').validators, [])
def test_related_model_is_unique(self):
data = {'username': 'existing', 'email': 'new-email@example.com'}
data = {'username': 'Existing', 'email': 'new-email@example.com'}
rs = RelatedModelSerializer(data=data)
self.assertFalse(rs.is_valid())
self.assertEqual(rs.errors,