I have a SerializerMethodField that make some heavy computation. I also use the same method into another SerializerMethodField of the same serializer. How can I cache the result of the first one, so I run only once the heavy computation?
Since the computation is common between two methods of the same serializer, you can use the cached_property decorator. This will cache the result of the method on the model instance, and the result will persist as long as the instance does.
from django.utils.functional import cached_property
class Person(models.Model):
@cached_property
def friends(self):
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With