如何在Django中使cache_page无效? [英] How to invalidate cache_page in Django?

查看:313
本文介绍了如何在Django中使cache_page无效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题出在这里:我有博客应用,并且将帖子输出视图缓存了5分钟。

Here is the problem: I have blog app and I cache the post output view for 5 minutes.

@cache_page(60 * 5)
def article(request, slug):
    ...

但是,只要将新评论添加到帖子中,我都想使缓存无效。
我想知道如何做到最好?

However, I'd like to invalidate the cache whenever a new comment is added to the post. I'm wondering how best to do so?

我见过,但是已经过时了。

I've seen this related question, but it is outdated.

推荐答案

我将以某种不同的方式进行缓存:

I would cache in a bit different way:

def article(request, slug):
    cached_article = cache.get('article_%s' % slug)
    if not cached_article:
        cached_article = Article.objects.get(slug=slug)
        cache.set('article_%s' % slug, cached_article, 60*5)

    return render(request, 'article/detail.html', {'article':cached_article})

然后将新注释保存到本文对象:

then saving the new comment to this article object:

# ...
# add the new comment to this article object, then
if cache.get('article_%s' % article.slug): 
    cache.delete('article_%s' % article.slug)
# ...

这篇关于如何在Django中使cache_page无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆