Closes #3937. Support callable as the value of initial for any serializer.Field

This commit is contained in:
Erick Wilder 2016-02-17 10:52:21 +01:00
parent 79dad012b0
commit 8109752061
2 changed files with 20 additions and 0 deletions

View File

@ -370,6 +370,8 @@ class Field(object):
Return a value to use when the field is being returned as a primitive
value, without any object instance.
"""
if callable(self.initial):
return self.initial()
return self.initial
def get_value(self, dictionary):

View File

@ -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:
def setup(self):
class TestSerializer(serializers.Serializer):