-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #4146 from xiaohanyu/bug-fix-unique-validator-erro…
…r-with-related-field Fix #3844, refine validator for fields with <source=> kwargs
- Loading branch information
Showing
2 changed files
with
28 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,6 +4,7 @@ | |
from django.test import TestCase | ||
|
||
from rest_framework import serializers | ||
from rest_framework.validators import UniqueValidator | ||
|
||
|
||
def dedent(blocktext): | ||
|
@@ -22,6 +23,20 @@ class Meta: | |
model = UniquenessModel | ||
|
||
|
||
class RelatedModel(models.Model): | ||
user = models.OneToOneField(UniquenessModel, on_delete=models.CASCADE) | ||
email = models.CharField(unique=True, max_length=80) | ||
|
||
|
||
class RelatedModelSerializer(serializers.ModelSerializer): | ||
username = serializers.CharField(source='user.username', | ||
validators=[UniqueValidator(queryset=UniquenessModel.objects.all())]) # NOQA | ||
|
||
class Meta: | ||
model = RelatedModel | ||
fields = ('username', 'email') | ||
|
||
|
||
class AnotherUniquenessModel(models.Model): | ||
code = models.IntegerField(unique=True) | ||
|
||
|
@@ -73,6 +88,16 @@ def test_doesnt_pollute_model(self): | |
self.assertEqual( | ||
AnotherUniquenessModel._meta.get_field('code').validators, []) | ||
|
||
def test_related_model_is_unique(self): | ||
data = {'username': 'existing', 'email': '[email protected]'} | ||
rs = RelatedModelSerializer(data=data) | ||
self.assertFalse(rs.is_valid()) | ||
self.assertEqual(rs.errors, | ||
{'username': ['This field must be unique.']}) | ||
data = {'username': 'new-username', 'email': '[email protected]'} | ||
rs = RelatedModelSerializer(data=data) | ||
self.assertTrue(rs.is_valid()) | ||
|
||
|
||
# Tests for `UniqueTogetherValidator` | ||
# ----------------------------------- | ||
|