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

    Without Cache

    With Cache

    Cooking food every time

    Reheating food

    Reading from book

    Bookmark

    Caching Basics

    What Can Be Cached?

    • HTML pages

    • Database query results

    • API responses

    • Computed values

    • Template fragments

    Types of Caching in Django

    Type

    Description

    Per-site cache

    Cache whole website

    Per-view cache

    Cache specific views

    Template fragment cache

    Cache part of template

    Low-level cache

    Cache custom data

    Cache Backends

    Common Cache Backends

    Backend

    Use Case

    Local Memory

    Development

    File-based

    Small apps

    Database

    Simple production

    Redis / Memcached

    High performance

    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

    Without Cache

    With Cache

    Multiple DB hits

    Single DB hit

    Slow response

    Fast response

    High CPU usage

    Low CPU usage

    Best Places to Use Cache

    ✔ Homepage
    ✔ Dashboard
    ✔ Product listing
    ✔ Reports
    ✔ API responses

    Cache Timeout Strategy

    Data Type

    Timeout

    Static content

    Long

    Frequently updated

    Short

    User specific

    Very short




    Caching vs Database Indexing

    Caching

    Indexing

    Stores data

    Speeds search

    Reduces queries

    Improves query execution

    Application level

    DB level