From 905a5579dfaa717ad4210ddd285267bb9bbb9a43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=B4mulo=20Oliveira?= Date: Fri, 1 Dec 2017 06:54:25 -0200 Subject: [PATCH] Non-required fields with 'allow_null=True' should not imply a default value (#5639) Ref #5518. --- rest_framework/fields.py | 4 ++-- tests/test_serializer.py | 8 ++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 55c2fe48e9..a710df7b48 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -442,10 +442,10 @@ def get_attribute(self, instance): except (KeyError, AttributeError) as exc: if self.default is not empty: return self.get_default() - if self.allow_null: - return None if not self.required: raise SkipField() + if self.allow_null: + return None msg = ( 'Got {exc_type} when attempting to get a value for field ' '`{field}` on serializer `{serializer}`.\nThe serializer ' diff --git a/tests/test_serializer.py b/tests/test_serializer.py index 23c6ec2c10..0c30deb916 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -372,6 +372,14 @@ def create(self, validated_data): serializer.save() assert serializer.data == {'included': 'abc'} + def test_not_required_output_for_allow_null_field(self): + class ExampleSerializer(serializers.Serializer): + omitted = serializers.CharField(required=False, allow_null=True) + included = serializers.CharField() + + serializer = ExampleSerializer({'included': 'abc'}) + assert 'omitted' not in serializer.data + class TestDefaultOutput: def setup(self):