Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up

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 cachingUpdateCacheMiddleware and FetchFromCacheMiddleware cache 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 APIcache.get, cache.set, and cache.get_or_set for 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.

All Django interview questions

Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up as