How to invalidate cache_page in Django?

纵饮孤独 提交于 2019-12-07 02:18:25

问题


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:


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)
# ...


来源:https://stackoverflow.com/questions/33749369/how-to-invalidate-cache-page-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!