django - 如何在 django 中缓存模型方法?

标签 django django-cache

我有这个模型:

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分钟。

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

最佳答案

我想您可以使用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]

希望这对您有用。

关于django - 如何在 django 中缓存模型方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34189341/

相关文章:

django - 我可以强制 Django 的每站点缓存仅使用每个页面的路径作为其键吗?

python - 当我删除帖子时,用户登录信息也会被删除

python - Django 网站中 Python 日志记录 RotatingFileHandler 的问题

python - 如何在 tastypie 中强制设置某些过滤器?

django - 一起使用django-nose和django-celery-单元测试

python - 在创建/编辑 View 中构建 Django ModelForm 的正确方法是什么?

django:将查询集保存到 session

django - 如何仅为未经身份验证的用户缓存 View ?

django - 如何有效地使几个 Django 缓存值无效?

python - 基本服务器资源上的 Django 缓存 : Caching thousands of queries for a long time,