Caching (Django)

Caching in Django stores expensive results so repeated requests are served fast. It offers per-view caching, template-fragment caching, and a low-level cache API, backed by memory, the database, files, or Redis/Memcached.

Django

Caching trades freshness for speed by saving computed results. Django provides several granularities: the per-site or per-view cache (@cache_page) stores a whole rendered response; the {% cache %} template tag caches a fragment of a page; and the low-level cache API (cache.get/cache.set) caches arbitrary values you compute.

You configure backends in the CACHES setting. Local-memory cache is the default and fine for development; production uses a shared store like Redis or Memcached so all server processes share one cache. Each cached entry has a timeout after which it expires and is recomputed.

The hard part of caching is invalidation — making sure stale data does not linger after the underlying data changes. Use sensible timeouts, version your cache keys, or clear specific keys when related models are saved (often via signals).

Syntax

from django.core.cache import cache
cache.set("key", value, 300)

Examples

Python

from django.views.decorators.cache import cache_page
from django.core.cache import cache

@cache_page(60 * 15)  # cache this view for 15 minutes
def report(request):
    ...

# low-level API
value = cache.get("stats")
if value is None:
    value = expensive()
    cache.set("stats", value, 300)

Learn it in a lesson

See also

Back to the Dictionary