How does caching work in Django, and what are the different caching levels?
Django exposes several granularities, and choosing the right one matters more than choosing the backend.
- Per-site caching —
UpdateCacheMiddlewareandFetchFromCacheMiddlewarecache entire pages. Simple, but wrong for anything personalised. - Per-view caching —
@cache_page(60 * 15)on a specific view. Good for public pages such as a listing or a blog post. - Template fragment caching —
{% cache 300 sidebar request.user.id %}around an expensive block, keyed by whatever makes it vary. This is often the best trade-off for a page that is mostly dynamic with one costly component. - The low-level API —
cache.get,cache.set, andcache.get_or_setfor caching a specific computation or query result. The most control and usually the right answer.
Backends: Redis or Memcached in production, local-memory for development, and dummy for tests.
The hard part is invalidation. Options are a short timeout and tolerating staleness, deleting the key in a post_save signal, or including a version marker in the cache key so a new value simply produces a new key and the old one expires on its own. The last approach avoids the race conditions the other two have.





