Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework: how to cache the result of SerializerMethodField?

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?

like image 383
user1518217 Avatar asked Oct 23 '25 18:10

user1518217


1 Answers

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):
        ...
like image 69
arjunattam Avatar answered Oct 27 '25 01:10

arjunattam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!