Merge pull request #5375 from rpkilby/related-source-serialization

Fix default value handling for dotted sources
This commit is contained in:
Carlton Gibson 2017-08-31 08:52:32 +02:00 committed by GitHub
commit bafb3ec22a
2 changed files with 13 additions and 3 deletions

View File

@ -93,9 +93,6 @@ def get_attribute(instance, attrs):
Also accepts either attribute lookup on objects or dictionary lookups.
"""
for attr in attrs:
if instance is None:
# Break out early if we get `None` at any point in a nested lookup.
return None
try:
if isinstance(instance, collections.Mapping):
instance = instance[attr]

View File

@ -411,6 +411,19 @@ class TestDefaultOutput:
serializer = self.Serializer(instance)
assert serializer.data == {'has_default': 'def', 'has_default_callable': 'ghi', 'no_default': 'abc'}
def test_default_for_source_source(self):
"""
'default="something"' should be used when a traversed attribute is missing from input.
"""
class Serializer(serializers.Serializer):
traversed = serializers.CharField(default='x', source='traversed.attr')
assert Serializer({}).data == {'traversed': 'x'}
assert Serializer({'traversed': {}}).data == {'traversed': 'x'}
assert Serializer({'traversed': None}).data == {'traversed': 'x'}
assert Serializer({'traversed': {'attr': 'abc'}}).data == {'traversed': 'abc'}
class TestCacheSerializerData:
def test_cache_serializer_data(self):