如何在 Django 中缓存模型方法?

How to cache a model method in django?

我有这个型号:

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)


    def last_post(self):
        if self.post_set.count():
            return self.post_set.order_by("-created")[0]

我注意到 last_post 创建了一个非常昂贵且频繁的 运行 查询。所以我想缓存它5分钟。

我知道如何在视图中缓存查询集,但last_post绕过视图并直接在模板中调用。非常感谢您关于如何缓存它的提示。

我想您可以使用 https://pypi.python.org/pypi/cached-property/1.2.0

中的 cached_property_with_ttl
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]

希望这对你有用。

编辑:@Yassine Belmamoun 指出这行不通,因为实例随请求而死。

原回答:

正如@Thomas Druez 所说,Django 现在有一个内置的 cached_property:

from django.utils.functional import cached_property

class Article(models.Model):

    @cached_property
    def last_post(self):
        if self.post_set.count():
            return self.post_set.order_by("-created")[0]

但是,我不知道您是否可以设置 5 分钟的过期时间。同一页面显示“只要实例存在,缓存的结果就会持续存在。”