Skip to content

Commit 7ed50ca

Browse files
committed
not required read_only Fields with allow_null True
Since encode#5639 we are unable to render fields that were rendered previously with `allow_null=True`. Backward compatibility is not preserved, because `required=True` and `read_only=True` are conflicting, so in our case, some fields just disappeared and it seems there is not way to get them back. I'm not sure about the fix, but the regression test is probably right.
1 parent 6602171 commit 7ed50ca

File tree

2 files changed

+8
-0
lines changed

2 files changed

+8
-0
lines changed

rest_framework/fields.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,8 @@ def get_attribute(self, instance):
442442
except (KeyError, AttributeError) as exc:
443443
if self.default is not empty:
444444
return self.get_default()
445+
if self.read_only and self.allow_null:
446+
return None
445447
if not self.required:
446448
raise SkipField()
447449
if self.allow_null:

tests/test_serializer.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,10 +384,16 @@ def create(self, validated_data):
384384
def test_not_required_output_for_allow_null_field(self):
385385
class ExampleSerializer(serializers.Serializer):
386386
omitted = serializers.CharField(required=False, allow_null=True)
387+
ommited_read_only = serializers.CharField(
388+
required=False,
389+
read_only=True,
390+
allow_null=True
391+
)
387392
included = serializers.CharField()
388393

389394
serializer = ExampleSerializer({'included': 'abc'})
390395
assert 'omitted' not in serializer.data
396+
assert serializer.data['ommited_read_only'] is None
391397

392398

393399
class TestDefaultOutput:

0 commit comments

Comments
 (0)