mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-02-09 08:00:52 +03:00
Closes #3937. Support callable as the value of initial
for any serializer.Field
This commit is contained in:
parent
79dad012b0
commit
8109752061
|
@ -370,6 +370,8 @@ class Field(object):
|
||||||
Return a value to use when the field is being returned as a primitive
|
Return a value to use when the field is being returned as a primitive
|
||||||
value, without any object instance.
|
value, without any object instance.
|
||||||
"""
|
"""
|
||||||
|
if callable(self.initial):
|
||||||
|
return self.initial()
|
||||||
return self.initial
|
return self.initial
|
||||||
|
|
||||||
def get_value(self, dictionary):
|
def get_value(self, dictionary):
|
||||||
|
|
|
@ -191,6 +191,24 @@ class TestInitial:
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class TestInitialWithCallable:
|
||||||
|
def setup(self):
|
||||||
|
def initial_value():
|
||||||
|
return 123
|
||||||
|
|
||||||
|
class TestSerializer(serializers.Serializer):
|
||||||
|
initial_field = serializers.IntegerField(initial=initial_value)
|
||||||
|
self.serializer = TestSerializer()
|
||||||
|
|
||||||
|
def test_initial_should_accept_callable(self):
|
||||||
|
"""
|
||||||
|
Follows the default ``Field.initial`` behaviour where they accept a
|
||||||
|
callable to produce the initial value"""
|
||||||
|
assert self.serializer.data == {
|
||||||
|
'initial_field': 123,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
class TestLabel:
|
class TestLabel:
|
||||||
def setup(self):
|
def setup(self):
|
||||||
class TestSerializer(serializers.Serializer):
|
class TestSerializer(serializers.Serializer):
|
||||||
|
|
Loading…
Reference in New Issue
Block a user