Skip to content

Commit 905a557

Browse files
RomuloOliveiracarltongibson
authored andcommitted
Non-required fields with 'allow_null=True' should not imply a default value (encode#5639)
Ref encode#5518.
1 parent 97f7a82 commit 905a557

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

rest_framework/fields.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -442,10 +442,10 @@ 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.allow_null:
446-
return None
447445
if not self.required:
448446
raise SkipField()
447+
if self.allow_null:
448+
return None
449449
msg = (
450450
'Got {exc_type} when attempting to get a value for field '
451451
'`{field}` on serializer `{serializer}`.\nThe serializer '

tests/test_serializer.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,14 @@ def create(self, validated_data):
372372
serializer.save()
373373
assert serializer.data == {'included': 'abc'}
374374

375+
def test_not_required_output_for_allow_null_field(self):
376+
class ExampleSerializer(serializers.Serializer):
377+
omitted = serializers.CharField(required=False, allow_null=True)
378+
included = serializers.CharField()
379+
380+
serializer = ExampleSerializer({'included': 'abc'})
381+
assert 'omitted' not in serializer.data
382+
375383

376384
class TestDefaultOutput:
377385
def setup(self):

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy