Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invalidate cache_page in Django?

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.

like image 684
Jand Avatar asked Nov 17 '15 04:11

Jand


Video Answer


1 Answers

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)
# ...
like image 74
doniyor Avatar answered Oct 08 '22 08:10

doniyor