【发布时间】: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 绕过视图并直接在模板中调用。非常感谢您对如何缓存它的提示。
【问题讨论】:
-
也许
cached_property是您所需要的。看:pydanny.com/cached-property.html -
听起来不错。您能否详细说明它作为一个完整的答案?
-
@cached_property将缓存整个请求的结果,而不是 5 分钟。这可能对你有用。 -
请注意,
cached_property装饰器现在在 Django 中可用:docs.djangoproject.com/en/1.9/ref/utils/…
标签: django django-cache