Skip to content

Commit

Permalink
not required read_only Fields with allow_null True
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
ticosax committed Jan 5, 2018
1 parent 6602171 commit 7ed50ca
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 0 deletions.
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,
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

0 comments on commit 7ed50ca

Please sign in to comment.