Skip to content

not required read_only Fields with allow_null #5708

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
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
Member

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