Oskar Persson Oskar Persson - 18 days ago 5
Python Question

Call method once to set multiple fields in Django Rest Framework serializer

How can I call the same method one time to set multiple fields with a Django Rest Framework serializer? This is what I do now but this clearly calls the method two times. How can I limit it to only be called once?

class MyModel(models.Model):
def GetTwoValues(self):
foo = []
bar = []

# expensive operation

return foo, bar

class MyModelSerializer(serializers.HyperlinkedModelSerializer):
foo = serializers.SerializerMethodField()
bar = serializers.SerializerMethodField()

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

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

class Meta:
model = MyModel
fields = ('FirstValue', 'SecondValue',)


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