diff --git a/rest_framework/fields.py b/rest_framework/fields.py index a710df7b48..043dd4a91b 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -442,6 +442,8 @@ def get_attribute(self, instance): except (KeyError, AttributeError) as exc: if self.default is not empty: return self.get_default() + if self.read_only and self.allow_null: + return None if not self.required: raise SkipField() if self.allow_null: diff --git a/tests/test_serializer.py b/tests/test_serializer.py index da1394515c..b00eb0dbd2 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -384,10 +384,16 @@ def create(self, validated_data): def test_not_required_output_for_allow_null_field(self): class ExampleSerializer(serializers.Serializer): omitted = serializers.CharField(required=False, allow_null=True) + ommited_read_only = serializers.CharField( + required=False, + read_only=True, + allow_null=True + ) included = serializers.CharField() serializer = ExampleSerializer({'included': 'abc'}) assert 'omitted' not in serializer.data + assert serializer.data['ommited_read_only'] is None class TestDefaultOutput: