Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
6 changes: 6 additions & 0 deletions tests/test_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

btw, the required=False is unnecessary here, as it's implied by read_only=True.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can take it out if you prefer

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:
Expand Down