Skip to content

Commit a543fae

Browse files
committed
Merge pull request #2766 from delinhabit/allow-null-list-serializer
Modify subtle ChildSerializer(many=True, allow_null=True) behavior.
2 parents 9a661f5 + bbd44ae commit a543fae

File tree

2 files changed

+57
-1
lines changed

2 files changed

+57
-1
lines changed

rest_framework/serializers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
LIST_SERIALIZER_KWARGS = (
4949
'read_only', 'write_only', 'required', 'default', 'initial', 'source',
5050
'label', 'help_text', 'style', 'error_messages', 'allow_empty',
51-
'instance', 'data', 'partial', 'context'
51+
'instance', 'data', 'partial', 'context', 'allow_null'
5252
)
5353

5454

tests/test_serializer_nested.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,3 +69,59 @@ def test_multipart_validate(self):
6969
input_data = QueryDict('nested[one]=1')
7070
serializer = self.Serializer(data=input_data)
7171
assert serializer.is_valid()
72+
73+
74+
class TestNestedSerializerWithMany:
75+
def setup(self):
76+
class NestedSerializer(serializers.Serializer):
77+
example = serializers.IntegerField(max_value=10)
78+
79+
class TestSerializer(serializers.Serializer):
80+
allow_null = NestedSerializer(many=True, allow_null=True)
81+
not_allow_null = NestedSerializer(many=True)
82+
83+
self.Serializer = TestSerializer
84+
85+
def test_null_allowed_if_allow_null_is_set(self):
86+
input_data = {
87+
'allow_null': None,
88+
'not_allow_null': [{'example': '2'}, {'example': '3'}]
89+
}
90+
expected_data = {
91+
'allow_null': None,
92+
'not_allow_null': [{'example': 2}, {'example': 3}]
93+
}
94+
serializer = self.Serializer(data=input_data)
95+
96+
assert serializer.is_valid(), serializer.errors
97+
assert serializer.validated_data == expected_data
98+
99+
def test_null_is_not_allowed_if_allow_null_is_not_set(self):
100+
input_data = {
101+
'allow_null': None,
102+
'not_allow_null': None
103+
}
104+
serializer = self.Serializer(data=input_data)
105+
106+
assert not serializer.is_valid()
107+
108+
expected_errors = {'not_allow_null': [serializer.error_messages['null']]}
109+
assert serializer.errors == expected_errors
110+
111+
def test_run_the_field_validation_even_if_the_field_is_null(self):
112+
class TestSerializer(self.Serializer):
113+
validation_was_run = False
114+
115+
def validate_allow_null(self, value):
116+
TestSerializer.validation_was_run = True
117+
return value
118+
119+
input_data = {
120+
'allow_null': None,
121+
'not_allow_null': [{'example': 2}]
122+
}
123+
serializer = TestSerializer(data=input_data)
124+
125+
assert serializer.is_valid()
126+
assert serializer.validated_data == input_data
127+
assert TestSerializer.validation_was_run

0 commit comments

Comments
 (0)