python 31 lines · 1 tab

Django caching with cache_page and cache decorator

Priya Sharma Jan 2026
1 tab
from django.core.cache import cache
from django.views.decorators.cache import cache_page
from django.utils.decorators import method_decorator
from django.views.generic import ListView, DetailView
from .models import Post


@method_decorator(cache_page(60 * 15), name='dispatch')  # 15 minutes
class PostListView(ListView):
    model = Post
    template_name = 'blog/post_list.html'


class PostDetailView(DetailView):
    model = Post
    template_name = 'blog/post_detail.html'

    def get_object(self):
        post_id = self.kwargs['pk']
        cache_key = f'post:{post_id}'

        # Try cache first
        post = cache.get(cache_key)

        if post is None:
            # Cache miss - fetch from database
            post = super().get_object()
            # Cache for 1 hour
            cache.set(cache_key, post, 60 * 60)

        return post
1 file · python Explain with highlit

I use Django's cache framework to avoid expensive queries and computations. The cache_page decorator caches entire view responses by URL. For more control, I use the low-level cache API to store query results or computed values. I set reasonable timeouts and use cache versioning to invalidate related keys. For view fragments, I use template caching. Redis is my preferred backend for production due to speed and data structures. I'm careful with cache keys to avoid collisions and consider query parameters when caching. Cache warming can preload frequently-accessed data.


Related snips

Share this code

Here's the card — post it anywhere.

Django caching with cache_page and cache decorator — share card
Link copied