Skip to content

Commit

Permalink
Non-required fields with 'allow_null=True' should not imply a default…
Browse files Browse the repository at this point in the history
… value (encode#5639)

Ref encode#5518.
  • Loading branch information
RomuloOliveira authored and Pierre Chiquet committed Mar 24, 2020
1 parent 3c5e34c commit 5024aec
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
4 changes: 2 additions & 2 deletions rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -442,10 +442,10 @@ def get_attribute(self, instance):
except (KeyError, AttributeError) as exc:
if self.default is not empty:
return self.get_default()
if self.allow_null:
return None
if not self.required:
raise SkipField()
if self.allow_null:
return None
msg = (
'Got {exc_type} when attempting to get a value for field '
'`{field}` on serializer `{serializer}`.\nThe serializer '
Expand Down
8 changes: 8 additions & 0 deletions tests/test_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,14 @@ def create(self, validated_data):
serializer.save()
assert serializer.data == {'included': 'abc'}

def test_not_required_output_for_allow_null_field(self):
class ExampleSerializer(serializers.Serializer):
omitted = serializers.CharField(required=False, allow_null=True)
included = serializers.CharField()

serializer = ExampleSerializer({'included': 'abc'})
assert 'omitted' not in serializer.data


class TestDefaultOutput:
def setup(self):
Expand Down

0 comments on commit 5024aec

Please sign in to comment.