Skip to content

Commit 5009aef

Browse files
Ryan P Kilbycarltongibson
authored andcommitted
Fields with 'allow_null=True' should imply a default serialization value (#5518)
* Add test for dotted source + allow_null * Field 'allow_null' implies 'default=None' * Field 'allow_null' provides serialization default
1 parent 1f693c3 commit 5009aef

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-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.allow_null:
446+
return None
445447
if not self.required:
446448
raise SkipField()
447449
msg = (

tests/test_serializer.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -449,6 +449,14 @@ class Serializer(serializers.Serializer):
449449
assert Serializer({'nested': {'a': '3', 'b': {}}}).data == {'nested': {'a': '3', 'c': '2'}}
450450
assert Serializer({'nested': {'a': '3', 'b': {'c': '4'}}}).data == {'nested': {'a': '3', 'c': '4'}}
451451

452+
def test_default_for_allow_null(self):
453+
# allow_null=True should imply default=None
454+
class Serializer(serializers.Serializer):
455+
foo = serializers.CharField()
456+
bar = serializers.CharField(source='foo.bar', allow_null=True)
457+
458+
assert Serializer({'foo': None}).data == {'foo': None, 'bar': None}
459+
452460

453461
class TestCacheSerializerData:
454462
def test_cache_serializer_data(self):

0 commit comments

Comments
 (0)