mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-08-07 22:04:48 +03:00
fix PostgreSQL fields DataError in unique validator
This commit is contained in:
parent
68312cb0bc
commit
f88bd2979a
|
@ -8,6 +8,7 @@ object creation, and makes it possible to switch between using the implicit
|
|||
"""
|
||||
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
|
||||
|
@ -59,7 +60,14 @@ class UniqueValidator(object):
|
|||
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
|
||||
|
||||
if exists:
|
||||
raise ValidationError(self.message)
|
||||
|
||||
def __repr__(self):
|
||||
|
|
|
@ -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):
|
||||
|
@ -41,6 +42,7 @@ class TestUniquenessValidation(TestCase):
|
|||
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
|
||||
|
||||
|
@ -73,6 +75,12 @@ class TestUniquenessValidation(TestCase):
|
|||
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`
|
||||
# -----------------------------------
|
||||
|
|
Loading…
Reference in New Issue
Block a user