mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-01-23 15:54:16 +03:00
Enforce uniqueness validation for relational fields
This commit is contained in:
parent
3a3e2bf57d
commit
6bfed6f852
|
@ -224,6 +224,8 @@ class Field(object):
|
|||
"""
|
||||
if self.default is empty:
|
||||
raise SkipField()
|
||||
if is_simple_callable(self.default):
|
||||
return self.default()
|
||||
return self.default
|
||||
|
||||
def run_validation(self, data=empty):
|
||||
|
|
|
@ -219,6 +219,9 @@ def get_relation_kwargs(field_name, relation_info):
|
|||
kwargs['required'] = False
|
||||
if model_field.null:
|
||||
kwargs['allow_null'] = True
|
||||
if getattr(model_field, 'unique', False):
|
||||
validator = UniqueValidator(queryset=model_field.model._default_manager)
|
||||
kwargs['validators'] = [validator]
|
||||
|
||||
return kwargs
|
||||
|
||||
|
|
|
@ -248,7 +248,7 @@ class TestRelationalFieldMappings(TestCase):
|
|||
TestSerializer():
|
||||
id = IntegerField(label='ID', read_only=True)
|
||||
foreign_key = PrimaryKeyRelatedField(queryset=ForeignKeyTargetModel.objects.all())
|
||||
one_to_one = PrimaryKeyRelatedField(queryset=OneToOneTargetModel.objects.all())
|
||||
one_to_one = PrimaryKeyRelatedField(queryset=OneToOneTargetModel.objects.all(), validators=[<UniqueValidator(queryset=RelationalModel.objects.all())>])
|
||||
many_to_many = PrimaryKeyRelatedField(many=True, queryset=ManyToManyTargetModel.objects.all())
|
||||
through = PrimaryKeyRelatedField(many=True, read_only=True)
|
||||
""")
|
||||
|
@ -287,7 +287,7 @@ class TestRelationalFieldMappings(TestCase):
|
|||
TestSerializer():
|
||||
url = HyperlinkedIdentityField(view_name='relationalmodel-detail')
|
||||
foreign_key = HyperlinkedRelatedField(queryset=ForeignKeyTargetModel.objects.all(), view_name='foreignkeytargetmodel-detail')
|
||||
one_to_one = HyperlinkedRelatedField(queryset=OneToOneTargetModel.objects.all(), view_name='onetoonetargetmodel-detail')
|
||||
one_to_one = HyperlinkedRelatedField(queryset=OneToOneTargetModel.objects.all(), validators=[<UniqueValidator(queryset=RelationalModel.objects.all())>], view_name='onetoonetargetmodel-detail')
|
||||
many_to_many = HyperlinkedRelatedField(many=True, queryset=ManyToManyTargetModel.objects.all(), view_name='manytomanytargetmodel-detail')
|
||||
through = HyperlinkedRelatedField(many=True, read_only=True, view_name='throughtargetmodel-detail')
|
||||
""")
|
||||
|
|
Loading…
Reference in New Issue
Block a user