How to Use Caching in Django for Faster Web Apps
In Django, you use caching by configuring a cache backend in
settings.py and then using Django's cache API to store and retrieve data. This helps reduce database hits and speeds up page loading by saving computed data temporarily.Syntax
Django caching involves setting up a cache backend and using the cache object to store and retrieve data.
cache.set(key, value, timeout): Saves data with a key and optional expiration time.cache.get(key, default=None): Retrieves data by key or returns default if not found.cache.delete(key): Removes data by key.
python
from django.core.cache import cache # Save data in cache for 300 seconds cache.set('my_key', 'my_value', 300) # Retrieve data from cache value = cache.get('my_key') # Delete data from cache cache.delete('my_key')
Example
This example shows how to cache a view result to avoid recalculating it on every request.
python
from django.core.cache import cache from django.http import HttpResponse import time def slow_view(request): cached_response = cache.get('slow_view_response') if cached_response: return HttpResponse(cached_response) # Simulate slow processing time.sleep(3) response = 'This is a slow response generated at ' + time.ctime() # Cache the response for 60 seconds cache.set('slow_view_response', response, 60) return HttpResponse(response)
Output
When you first visit the view, it waits 3 seconds and shows the response with the current time. Subsequent visits within 60 seconds show the cached response instantly without delay.
Common Pitfalls
Common mistakes when using Django caching include:
- Not configuring a cache backend in
settings.py, so caching silently fails. - Using the default
LocMemCachein production, which is not shared across processes. - Forgetting to set a timeout, causing stale data to persist indefinitely.
- Not invalidating or deleting cache keys when underlying data changes, leading to outdated content.
python
from django.core.cache import cache # Wrong: No timeout, cache never expires cache.set('key', 'value', timeout=None) # Right: Set a timeout to expire cache cache.set('key', 'value', timeout=300)
Quick Reference
Here is a quick cheat sheet for Django caching commands:
| Command | Description |
|---|---|
| cache.set(key, value, timeout) | Store data in cache with expiration time in seconds |
| cache.get(key, default=None) | Retrieve data from cache or return default if missing |
| cache.delete(key) | Remove data from cache by key |
| cache.clear() | Clear all cache data |
| cache.get_or_set(key, default, timeout) | Get data or set it if missing in one call |
Key Takeaways
Configure a cache backend in settings.py before using caching.
Use cache.set and cache.get to store and retrieve data efficiently.
Always set a timeout to avoid stale cache data.
Invalidate or delete cache keys when underlying data changes.
Avoid using local memory cache in production; prefer Redis or Memcached.