[Solved]-How to cache a model method in django?

8👍

I suppose that you can use cached_property_with_ttl from https://pypi.python.org/pypi/cached-property/1.2.0

from cached_property import cached_property_with_ttl

class Article(models.Model):
    title = models.CharField(max_length=300, blank=False)
    body = models.TextField(max_length=10000, blank=False)
    created = models.DateTimeField(auto_now_add=True)

    @cached_property_with_ttl(ttl=5)
    def last_post(self):
        if self.post_set.count():
            return self.post_set.order_by("-created")[0]

Hope this will work for you.

2👍

EDIT : @Yassine Belmamoun pointed out that this won’t work because the instance dies with the request. I’m keeping it so people have an example of what NOT to do.

Original answer (DO NOT USE):

As @Thomas Druez said, Django now has a built-in cached_property:

from django.utils.functional import cached_property

class Article(models.Model):

    @cached_property
    ## DON'T USE THIS; IT DOES NOT WORK
    ## KEEPING AS REFERENCE OF WHAT NOT TO DO
    def last_post(self):
        if self.post_set.count():
            return self.post_set.order_by("-created")[0]

Leave a comment