[Solved]-Call method once to set multiple fields in Django Rest Framework serializer


There are a few options:

1) Store the values so that the expensive method is called only once. E.g.:

def _get_two_values(self, obj):
    if not hasattr(self, '_two_values'):
        self._two_values = obj.GetTwoValues()
    return self._two_values

def get_foo(self, obj):
    foo, _ = self._get_two_values(obj)
    return foo

def get_bar(self, obj):
    _, bar = self._get_two_values(obj)
    return bar

2) Remove both fields from the serializer and assign both values in the serializer’s to_representation method. E.g.:

def to_representation(self, obj):
    data = super().to_representation(obj)
    foo, bar = obj.GetTwoValues()
    data['foo'] = foo
    data['bar'] = bar
    return data

Leave a comment