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):