diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index b62901a79..56dbac2d3 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -48,7 +48,7 @@ from rest_framework.relations import * # NOQA # isort:skip LIST_SERIALIZER_KWARGS = ( 'read_only', 'write_only', 'required', 'default', 'initial', 'source', 'label', 'help_text', 'style', 'error_messages', 'allow_empty', - 'instance', 'data', 'partial', 'context' + 'instance', 'data', 'partial', 'context', 'allow_null' ) diff --git a/tests/test_serializer_nested.py b/tests/test_serializer_nested.py index b14a58c9e..22d4deca1 100644 --- a/tests/test_serializer_nested.py +++ b/tests/test_serializer_nested.py @@ -69,3 +69,59 @@ class TestNotRequiredNestedSerializer: input_data = QueryDict('nested[one]=1') serializer = self.Serializer(data=input_data) assert serializer.is_valid() + + +class TestNestedSerializerWithMany: + def setup(self): + class NestedSerializer(serializers.Serializer): + example = serializers.IntegerField(max_value=10) + + class TestSerializer(serializers.Serializer): + allow_null = NestedSerializer(many=True, allow_null=True) + not_allow_null = NestedSerializer(many=True) + + self.Serializer = TestSerializer + + def test_null_allowed_if_allow_null_is_set(self): + input_data = { + 'allow_null': None, + 'not_allow_null': [{'example': '2'}, {'example': '3'}] + } + expected_data = { + 'allow_null': None, + 'not_allow_null': [{'example': 2}, {'example': 3}] + } + serializer = self.Serializer(data=input_data) + + assert serializer.is_valid(), serializer.errors + assert serializer.validated_data == expected_data + + def test_null_is_not_allowed_if_allow_null_is_not_set(self): + input_data = { + 'allow_null': None, + 'not_allow_null': None + } + serializer = self.Serializer(data=input_data) + + assert not serializer.is_valid() + + expected_errors = {'not_allow_null': [serializer.error_messages['null']]} + assert serializer.errors == expected_errors + + def test_run_the_field_validation_even_if_the_field_is_null(self): + class TestSerializer(self.Serializer): + validation_was_run = False + + def validate_allow_null(self, value): + TestSerializer.validation_was_run = True + return value + + input_data = { + 'allow_null': None, + 'not_allow_null': [{'example': 2}] + } + serializer = TestSerializer(data=input_data) + + assert serializer.is_valid() + assert serializer.validated_data == input_data + assert TestSerializer.validation_was_run