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

fix PostgreSQL fields DataError in unique validator #3493

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion rest_framework/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"""
from __future__ import unicode_literals

from django.db import DataError
from django.utils.translation import ugettext_lazy as _

from rest_framework.compat import unicode_to_repr
Expand Down Expand Up @@ -59,7 +60,14 @@ def __call__(self, value):
queryset = self.queryset
queryset = self.filter_queryset(value, queryset)
queryset = self.exclude_current_instance(queryset)
if queryset.exists():

# catch DataError for PostgrSQL fields
try:
exists = queryset.exists()
except DataError:
return
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I would probably prefer exists = False here.


if exists:
raise ValidationError(self.message)

def __repr__(self):
Expand Down
8 changes: 8 additions & 0 deletions tests/test_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ def dedent(blocktext):

class UniquenessModel(models.Model):
username = models.CharField(unique=True, max_length=100)
ip = models.GenericIPAddressField(protocol='IPv4', unique=True, blank=True, null=True)


class UniquenessSerializer(serializers.ModelSerializer):
Expand All @@ -41,6 +42,7 @@ def test_repr(self):
UniquenessSerializer():
id = IntegerField(label='ID', read_only=True)
username = CharField(max_length=100, validators=[<UniqueValidator(queryset=UniquenessModel.objects.all())>])
ip = IPAddressField(allow_null=True, required=False, validators=[<django.core.validators.RegexValidator object>, <UniqueValidator(queryset=UniquenessModel.objects.all())>])
""")
assert repr(serializer) == expected

Expand Down Expand Up @@ -73,6 +75,12 @@ def test_doesnt_pollute_model(self):
self.assertEqual(
AnotherUniquenessModel._meta.get_field('code').validators, [])

def test_data_error(self):
data = {'ip': 'test', 'username': 'test'}
serializer = UniquenessSerializer(data=data)
assert not serializer.is_valid()
assert serializer.errors == {'ip': [u'Enter a valid IPv4 address.', u'Enter a valid IPv4 or IPv6 address.']}


# Tests for `UniqueTogetherValidator`
# -----------------------------------
Expand Down