Caching
- Learn how to implement caching in Django to improve application performance.
What is Caching?
Caching means storing frequently used data temporarily so that it can be served faster next time.
Instead of:
Request → DB → Processing → Response
We use:
Request → Cache → Response
Why Caching is Important?
Improves website speed
Reduces database load
Handles more users
Enhances user experience
Saves server resources
Real-Life Analogy
Caching Basics
What Can Be Cached?
HTML pages
Database query results
API responses
Computed values
Template fragments
Types of Caching in Django
Cache Backends
Common Cache Backends
Configure Cache (Basic Setup)
Local Memory Cache Setup
settings.py
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'unique-cache-name',
}
}
Description
Best for development
Stored in server memory
Per-View Caching
Cache a View for Specific Time
Cache View Using Decorator
views.py
from django.views.decorators.cache import cache_page
from django.http import HttpResponse
@cache_page(60 * 5) # Cache for 5 minutes
def home(request):
return HttpResponse("Home Page")
Description
View response cached for 5 minutes
Next request served from cache
Cache Class-Based Views
Cache CBV
from django.views.decorators.cache import cache_page
from django.utils.decorators import method_decorator
from django.views import View
@method_decorator(cache_page(60), name='dispatch')
class DashboardView(View):
def get(self, request):
return HttpResponse("Dashboard")
Template Fragment Caching
Cache Only Heavy Parts of Template
Template Fragment Cache
{% load cache %}
{% cache 300 sidebar %}
<h3>Popular Courses</h3>
<!-- heavy content -->
{% endcache %}
Description
Caches sidebar for 5 minutes
Page loads faster
Low-Level Caching
Cache Custom Data Manually
Low-Level Cache Example
from django.core.cache import cache
def get_course_count():
count = cache.get('course_count')
if not count:
count = Course.objects.count()
cache.set('course_count', count, timeout=300)
return count
Description
First request hits DB
Later requests use cached value
Database Query Caching
Cache QuerySet Result
def student_list():
students = cache.get('students')
if not students:
students = list(Student.objects.all())
cache.set('students', students, 600)
return students
Clearing Cache
Clear Cache Manually
from django.core.cache import cache
cache.delete('course_count')
cache.clear()
Performance Improvement Using Caching
How Caching Improves Performance
Best Places to Use Cache
✔ Homepage
✔ Dashboard
✔ Product listing
✔ Reports
✔ API responsesCache Timeout Strategy
Caching vs Database Indexing