Skip to content
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

Non-required fields with 'allow_null=True' should not imply a default value #5639

Merged
merged 1 commit into from
Dec 1, 2017
Merged
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
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