Caching Strategies (Redis, Memcached)
Caching stores frequently accessed data in fast storage (memory) to avoid expensive database queries and computations. Django supports multiple cache backends — Redis is the most popular choice for production.
20 min•By Priygop Team•Updated 2026
Django Caching
- Per-view cache — @cache_page(timeout) decorator
- Template fragment cache — {% cache timeout key %}
- Low-level cache — cache.get(), cache.set()
- Cache backends: Redis, Memcached, database, file, locmem
- Redis is recommended for production (fast, persistent)
- Cache invalidation — Clear cache when data changes
- pip install django-redis for Redis backend
Caching Examples
Caching Examples
# settings.py — Redis cache backend
# pip install django-redis
# CACHES = {
# 'default': {
# 'BACKEND': 'django.core.cache.backends.redis.RedisCache',
# 'LOCATION': 'redis://127.0.0.1:6379/1',
# 'TIMEOUT': 300, # 5 minutes default
# }
# }
# Per-view caching
# from django.views.decorators.cache import cache_page
# @cache_page(60 * 15) # Cache for 15 minutes
# def post_list(request):
# posts = Post.objects.filter(published=True)
# return render(request, 'blog/list.html', {'posts': posts})
# Low-level cache API
# from django.core.cache import cache
# def get_popular_posts():
# key = 'popular_posts'
# posts = cache.get(key)
# if posts is None:
# posts = list(Post.objects.order_by('-views_count')[:10])
# cache.set(key, posts, 60 * 30) # Cache 30 minutes
# return posts
# Template fragment caching
# {% load cache %}
# {% cache 600 sidebar %}
# <!-- Expensive sidebar content -->
# {% for cat in categories %}
# <a href="{{ cat.get_absolute_url }}">{{ cat.name }} ({{ cat.post_count }})</a>
# {% endfor %}
# {% endcache %}
# Cache invalidation on save
# @receiver(post_save, sender=Post)
# def clear_post_cache(sender, **kwargs):
# cache.delete('popular_posts')Tip
Tip
Use Django's cache framework with Redis or Memcached. cache.set('key', value, timeout=300) for 5-minute cache.
Diagram
Loading diagram…
QuerySets are LAZY — no DB hit until evaluated.
Common Mistake
Warning
Caching without invalidation strategy. Stale cache causes bugs. Always cache.delete() when data changes.
Practice Task
Note
(1) Set up Redis caching. (2) Cache a queryset for 5 minutes. (3) Invalidate cache on model save signal.
Quick Quiz
Key Takeaways
- Caching stores frequently accessed data in fast storage (memory) to avoid expensive database queries and computations.
- Per-view cache — @cache_page(timeout) decorator
- Template fragment cache — {% cache timeout key %}
- Low-level cache — cache.get(), cache.set()