【问题标题】:How to cache a model method in django?如何在 django 中缓存模型方法?
【发布时间】:2015-12-09 21:28:54
【问题描述】:

我有这个模型:

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 绕过视图并直接在模板中调用。非常感谢您对如何缓存它的提示。

【问题讨论】:

标签: django django-cache


【解决方案1】:

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

希望这对你有用。

【讨论】:

  • 太棒了!唯一的问题是我使用的是 1.8。没有cached_property_with_ttl。有解决办法吗?
  • 这不是 django 实现。它是单独的包。
  • 好吧,我收到了这个错误from cached_property import cached_property_with_ttl ImportError: No module named cached_property。那么我应该如何在 1.8 中安装/导入它呢?
  • pip install cached_property
  • 在 Windows 和 Ubuntu 上没有问题。
【解决方案2】:

编辑:@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 分钟到期。同一页面显示“缓存的结果将与实例一样持续存在。”

【讨论】:

  • cached_property 装饰器“将持续存在,只要实例存在”。这意味着将为每个新请求计算结果。这行不通。
猜你喜欢
  • 2013-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-03
  • 2015-02-24
  • 2020-02-12
  • 1970-01-01
  • 2013-01-12
相关资源
最近更新 更多