This commit is contained in:
DERBOIS Aymeric 2014-08-16 13:36:44 +00:00
commit f98a1293a4
2 changed files with 27 additions and 0 deletions

View File

@ -1038,3 +1038,17 @@ class SerializerMethodField(Field):
def field_to_native(self, obj, field_name):
value = getattr(self.parent, self.method_name)(obj)
return self.to_native(value)
class SerializerLambdaField(Field):
"""
A field that gets its value by calling a lambda.
"""
def __init__(self, func, *args, **kwargs):
self.func = func
super(SerializerLambdaField, self).__init__(*args, **kwargs)
def field_to_native(self, obj, field_name):
value = self.func(obj)
return self.to_native(value)

View File

@ -1002,3 +1002,16 @@ class BooleanField(TestCase):
bool_field = serializers.BooleanField(required=True)
self.assertFalse(BooleanRequiredSerializer(data={}).is_valid())
class SerializerLambdaFieldTest(TestCase):
"""
Tests for the SerializerLambdaField field_to_native() behavior
"""
class Example():
my_test = 'Hey, this is a test !'
def test_field_to_native(self):
s = serializers.SerializerLambdaField(lambda obj: obj.my_test)
result = s.field_to_native(self.Example(), None)
self.assertEqual(result, 'Hey, this is a test !')