• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

Formal Definition

Django’s Cache Framework provides a unified API for storing and retrieving computed data across multiple backends (in-memory, database, filesystem, Redis, Memcached) with support for per-site, per-view, template fragment, and low-level caching, while performance optimization encompasses query optimization (select_related, prefetch_related), database indexing, and asynchronous task offloading via Celery.

Explanation

Caching solves the problem of repeated expensive computations (database queries, template rendering, API calls) by storing results for reuse. Django’s cache API (cache.get, cache.set, cache.get_or_set) abstracts the backend, allowing development with local memory cache and production with Redis/Memcached. Performance optimization complements caching by reducing the need for it — efficient queries, proper indexes, and background processing keep response times low even on cache misses.

How It Works

  1. Backend configuredCACHES = {'default': {'BACKEND': 'django.core.cache.backends.redis.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/1'}}
  2. Cache key generated — Unique string; make_key('my_key', version=2) includes prefix and version
  3. Set/Get operationscache.set(key, value, timeout=300); cache.get(key, default=None)
  4. Per-view caching@cache_page(60 * 15) decorator caches entire response
  5. Template fragment{% cache 500 sidebar request.user.id %}...{% endcache %}
  6. Low-level APIcache.add() (only if not exists), cache.incr(), cache.decr(), cache.delete_pattern() (Redis)

Visual Explanation

caching_performance View View Function Expensive computation CacheAPI cache.get(key) → Hit: return value → Miss: compute → cache.set() View->CacheAPI 1. Check cache QueryOpt Query Optimization select_related() prefetch_related() Indexing View->QueryOpt 3. Optimize queries Celery Celery Background Tasks Offload heavy work View->Celery 4. Offload async Backend Cache Backend Redis / Memcached / LocMem / Database CacheAPI->Backend 2. Backend ops

Semantic Network

semantic_caching_performance THIS Caching / Performance PRE1 Cache Framework API THIS--PRE1 built from PRE2 Cache Backends THIS--PRE2 built from PRE3 Query Optimization THIS--PRE3 built from OUT1 Per-View Caching THIS--OUT1 builds into OUT2 Template Fragment Caching THIS--OUT2 builds into OUT3 Low-Level Cache API THIS--OUT3 builds into OUT4 Redis / Memcached THIS--OUT4 builds into OUT5 Celery Background Jobs THIS--OUT5 builds into OUT6 Query Optimization THIS--OUT6 builds into CON1 Flask-Caching (Extension) THIS--CON1 contrasts with CON2 FastAPI Custom Caching THIS--CON2 contrasts with REL1 Middleware (Cache Middleware) THIS--REL1 related REL2 Database Indexes THIS--REL2 related

Key Properties

  • Backends: LocMemCache (dev, per-process), RedisCache (Django 4.0+, recommended), MemcachedCache, DatabaseCache, FileBasedCache
  • Key prefix: KEY_PREFIX prevents collisions in shared Redis; VERSION for cache invalidation on schema changes
  • Timeouts: timeout in seconds; None = forever; 0 = don’t cache
  • Cache middleware: UpdateCacheMiddleware + FetchFromCacheMiddleware for per-site caching (requires CommonMiddleware)
  • Query optimization: select_related (FK/O2O → JOIN), prefetch_related (M2M/reverse FK → separate query), only/defer (field subset), indexes in Meta

Connections

Edge Cases & Gotchas

  • LocMemCache in production: Per-process, not shared across workers; use Redis/Memcached
  • Cache stampede: Multiple workers compute same missing key; use cache.add() + lock or get_or_set with callable
  • Cache invalidation: Hard problem; versioned keys (cache.set(f'v{version}:key', val)) or signals on model save
  • Query optimization order: select_related before filter; prefetch_related with Prefetch object for filtered prefetch
  • Celery serialization: Default pickle; use json serializer for security; task args must be JSON-serializable