我有这个模型:
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/