Caching in Django optimizes application performance by reducing redundant data fetching and computation. In this guide, we explore Per-View, Template, and Low-Level caching techniques.
Django supports multiple caching layers depending on how granular control you need over cached data.
Per-view caching stores the complete output of a Django view for a defined time.
# Cache the entire view response for 15 minutes
from django.views.decorators.cache import cache_page
@cache_page(60 * 15)
def my_view(request):
return render(request, 'my_template.html')
Template caching stores specific sections of a template using template tags.
# Cache sidebar section inside the template
{% load cache %}
{% cache 600 sidebar %}
{% endcache %}Low-level caching gives full control to cache arbitrary data manually.
# Cache database result manually using cache API
from django.core.cache import cache
def my_view(request):
data = cache.get('my_data')
if not data:
data = get_data_from_db()
cache.set('my_data', data, timeout=900)
return render(request, 'my_template.html', {'data': data})
Cached responses are served instantly without re-executing the view or database queries.
Click "Fetch Data" to simulate a request. The first time, it mimics a slow Database Query. Subsequent clicks mimic a Cache Hit.