diff --git a/rest_framework/relations.py b/rest_framework/relations.py index c1c27174a..79f53ee50 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -64,6 +64,7 @@ class RelatedField(Field): 'when setting read_only=`True`.' ) kwargs.pop('many', None) + kwargs.pop('allow_empty', None) super(RelatedField, self).__init__(**kwargs) def __new__(cls, *args, **kwargs): diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py index 38c433155..9494b0af3 100644 --- a/rest_framework/utils/field_mapping.py +++ b/rest_framework/utils/field_mapping.py @@ -225,6 +225,7 @@ def get_relation_kwargs(field_name, relation_info): # If this field is read-only, then return early. # No further keyword arguments are valid. return kwargs + if model_field.has_default() or model_field.null: kwargs['required'] = False if model_field.null: @@ -234,6 +235,8 @@ def get_relation_kwargs(field_name, relation_info): if getattr(model_field, 'unique', False): validator = UniqueValidator(queryset=model_field.model._default_manager) kwargs['validators'] = kwargs.get('validators', []) + [validator] + if to_many and not model_field.blank: + kwargs['allow_empty'] = False return kwargs diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py index f9ef633c5..8f3f82b63 100644 --- a/tests/test_model_serializer.py +++ b/tests/test_model_serializer.py @@ -395,7 +395,7 @@ class TestRelationalFieldMappings(TestCase): id = IntegerField(label='ID', read_only=True) foreign_key = PrimaryKeyRelatedField(queryset=ForeignKeyTargetModel.objects.all()) one_to_one = PrimaryKeyRelatedField(queryset=OneToOneTargetModel.objects.all(), validators=[]) - many_to_many = PrimaryKeyRelatedField(many=True, queryset=ManyToManyTargetModel.objects.all()) + many_to_many = PrimaryKeyRelatedField(allow_empty=False, many=True, queryset=ManyToManyTargetModel.objects.all()) through = PrimaryKeyRelatedField(many=True, read_only=True) """) self.assertEqual(unicode_repr(TestSerializer()), expected) @@ -434,7 +434,7 @@ class TestRelationalFieldMappings(TestCase): 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(), validators=[], view_name='onetoonetargetmodel-detail') - many_to_many = HyperlinkedRelatedField(many=True, queryset=ManyToManyTargetModel.objects.all(), view_name='manytomanytargetmodel-detail') + many_to_many = HyperlinkedRelatedField(allow_empty=False, many=True, queryset=ManyToManyTargetModel.objects.all(), view_name='manytomanytargetmodel-detail') through = HyperlinkedRelatedField(many=True, read_only=True, view_name='throughtargetmodel-detail') """) self.assertEqual(unicode_repr(TestSerializer()), expected)