← Back to Chapters

Types of Caching: Per-View, Template, Low-Level

⚡ Types of Caching: Per-View, Template, Low-Level

? Quick Overview

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.

? Key Concepts

  • Caching improves response time
  • Reduces database and server load
  • Improves scalability

? Syntax / Theory

Django supports multiple caching layers depending on how granular control you need over cached data.

? Per-View Caching

Per-view caching stores the complete output of a Django view for a defined time.

? View Code Example
# 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

Template caching stores specific sections of a template using template tags.

? View Code Example
# Cache sidebar section inside the template
{% load cache %}
{% cache 600 sidebar %}
{% endcache %}

? Low-Level Caching

Low-level caching gives full control to cache arbitrary data manually.

? View Code Example
# 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})

? Live Output / Explanation

Cached responses are served instantly without re-executing the view or database queries.

? Use Cases

  • Static pages
  • Reusable UI components
  • Expensive database queries

? Interactive Simulation: The Speed Difference

Click "Fetch Data" to simulate a request. The first time, it mimics a slow Database Query. Subsequent clicks mimic a Cache Hit.

// Status log... waiting for input

✅ Tips & Best Practices

  • Cache only what is necessary
  • Use low-level caching for expensive operations
  • Clear cache when data updates

? Try It Yourself

  • Add per-view caching to a static page
  • Cache a navbar using template caching
  • Store API response using low-level caching