mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-02-03 13:14:30 +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
|
||||
value, without any object instance.
|
||||
"""
|
||||
if callable(self.initial):
|
||||
return self.initial()
|
||||
return self.initial
|
||||
|
||||
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:
|
||||
def setup(self):
|
||||
class TestSerializer(serializers.Serializer):
|
||||
|
|
Loading…
Reference in New Issue
Block a user