mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-22 17:47:04 +03:00
Docs about default value for dotted source, additional tests (#5489)
* Add docs note on dotted source + default value * Add additional dotted source tests
This commit is contained in:
parent
5d7b6e5b2f
commit
6221124e0d
|
@ -61,7 +61,7 @@ Note that setting a `default` value implies that the field is not required. Incl
|
|||
|
||||
### `source`
|
||||
|
||||
The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`.
|
||||
The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`. When serializing fields with dotted notation, it may be necessary to provide a `default` value if any object is not present or is empty during attribute traversal.
|
||||
|
||||
The value `source='*'` has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.
|
||||
|
||||
|
|
|
@ -424,6 +424,31 @@ class TestDefaultOutput:
|
|||
|
||||
assert Serializer({'traversed': {'attr': 'abc'}}).data == {'traversed': 'abc'}
|
||||
|
||||
def test_default_for_multiple_dotted_source(self):
|
||||
class Serializer(serializers.Serializer):
|
||||
c = serializers.CharField(default='x', source='a.b.c')
|
||||
|
||||
assert Serializer({}).data == {'c': 'x'}
|
||||
assert Serializer({'a': {}}).data == {'c': 'x'}
|
||||
assert Serializer({'a': None}).data == {'c': 'x'}
|
||||
assert Serializer({'a': {'b': {}}}).data == {'c': 'x'}
|
||||
assert Serializer({'a': {'b': None}}).data == {'c': 'x'}
|
||||
|
||||
assert Serializer({'a': {'b': {'c': 'abc'}}}).data == {'c': 'abc'}
|
||||
|
||||
def test_default_for_nested_serializer(self):
|
||||
class NestedSerializer(serializers.Serializer):
|
||||
a = serializers.CharField(default='1')
|
||||
c = serializers.CharField(default='2', source='b.c')
|
||||
|
||||
class Serializer(serializers.Serializer):
|
||||
nested = NestedSerializer()
|
||||
|
||||
assert Serializer({'nested': None}).data == {'nested': None}
|
||||
assert Serializer({'nested': {}}).data == {'nested': {'a': '1', 'c': '2'}}
|
||||
assert Serializer({'nested': {'a': '3', 'b': {}}}).data == {'nested': {'a': '3', 'c': '2'}}
|
||||
assert Serializer({'nested': {'a': '3', 'b': {'c': '4'}}}).data == {'nested': {'a': '3', 'c': '4'}}
|
||||
|
||||
|
||||
class TestCacheSerializerData:
|
||||
def test_cache_serializer_data(self):
|
||||
|
|
Loading…
Reference in New Issue
Block a user