Often  the content of a blog post won't change once it has been written.  However, comments on that blog post may change relatively frequently.

One way of dealing with this is to cache the blog page for a moderate amount of time using per-view caching, and use ajax to pull in the comments.  You can then cache the comments template seperately for a much shorter period of time.

You can even clear the comments cache for just that blog post using a hook/signal because it is easy to get the cache_key for a cached template fragment.

Here is an example:


<!-- comments_template.html -->
<!-- this is the template  that is ajaxed in... -->

{% load cache %}
{% extends "base.html" %}

<!-- assumes a path like '/get-comments/<id>/' where <id> is id of blog post -->
{% cache 300 comments request.get_full_path using="my_cache" %}

<!-- your html etc here -->
<!-- this database hit will be cached as this is where the queryset will be evaluated -->
{% for comment in blog.comments.all %}
    {% include "comment.html" with comment as comment %}
{% endfor %}

{% endcache %}

<!-- html for comment posting form here -->
<!-- not cached as csrf token would require a 'vary' cookie for each web user -->
    

You can get the cache_key for the blog post's comment fragment in a signal like this:

(django-comments sends the signal)


from django.core.cache.utils import make_template_fragment_key
from django.core.cache import caches
from django_comments.signals import comment_was_posted
from django.dispatch.dispatcher import receiver

@receiver(comment_was_posted)
def clear_comments_cache_for_post(sender, comment, request, **kwargs):
    # delete cache for just this blog post's comment fragment
    path = '/get-comments/%s/' % comment.object_pk
    cache = caches['my_cache']
    key = make_template_fragment_key('comments', [path, ])
    cache.delete(key)
    
Loading comments...
';