How to invalidate cache_page in Django?

2019-05-05 19:38发布

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.

1条回答
戒情不戒烟
2楼-- · 2019-05-05 20:14

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)
# ...
查看更多
登录 后发表回答