Django Caching
Caching can avoid repeated work, but it introduces a period when a response may be stale. Choose the key, lifetime and invalidation rule deliberately.
How it works
This example caches a public workshop count in the process-local backend. It demonstrates that a changed database value does not update the cached result automatically. A deployment with several processes needs a suitable shared backend if it expects shared cache state. Never cache a user-specific response under one public key, and avoid assuming cache availability is guaranteed for correctness-critical operations such as reserving seats.
Run in the supplied local Django project
This lesson uses Django 5.2.18 LTS with Python 3.12. Download the source downloader and run node download-project.mjs http://127.0.0.1:8000 with Node 22 while previewing locally. It creates a new bhylu-django-lab folder and refuses to overwrite an existing one. After deployment, the default base is bhylu.com; until then use your local preview URL.
Inside that new folder, create a virtual environment, install requirements.txt and run the complete lesson file shown below. Every lesson creates a fresh in-memory SQLite database and temporary upload storage. It does not edit the interactive lab’s db.sqlite3 or Bhylu’s database. The visible listing below is the lesson’s core code; its complete downloaded file includes the shared bootstrap.
Django does not run in Bhylu’s current browser playground. No Apache, MySQL or global PHP configuration change is needed. See the setup lesson for the full project and commands.
Example
Run .venv\Scripts\python.exe lessons\cache.py from the downloaded project root. Download the complete lesson file; keep it under lessons/. The project’s shared models, forms, views and fixture are prerequisites, not a hidden online runtime.
from django.core.cache import cache
key = "public-workshop-count:v1"
cache.set(key, Workshop.objects.public().count(), timeout=60)
Workshop.objects.filter(slug="wood-joints").update(published=True)
print(cache.get(key), Workshop.objects.public().count())
cache.delete(key)
print(cache.get(key) is None)
Expected result
2 3 True
The stale cached count is two while the database now contains three public workshops. Deleting the key removes that stale value. The example makes the tradeoff visible instead of describing every cache hit as current data.
Use Django’s versioned official documentation for exact API contracts and the deployment checklist before a separate release.