The low-level cache API lets you store and get data quickly in Django. It helps your app run faster by saving results you use often.
0
0
Low-level cache API in Django
Introduction
You want to save the result of a slow database query to reuse it later.
You want to store user session data temporarily to avoid repeated calculations.
You want to cache the output of a complex function to speed up your website.
You want to share data between different parts of your Django app quickly.
You want to reduce load on your database by caching frequent requests.
Syntax
Django
from django.core.cache import cache # Save data to cache cache.set('key', value, timeout=timeout_seconds) # Get data from cache value = cache.get('key', default=None) # Delete data from cache cache.delete('key')
cache.set saves data with a key and optional timeout (in seconds).
cache.get retrieves data by key; returns None or a default if not found.
Examples
This saves 'alice' under 'username' for 5 minutes, then gets it.
Django
cache.set('username', 'alice', timeout=300) user = cache.get('username')
Saves number 42 with no timeout (default cache timeout). Gets it or 0 if missing.
Django
cache.set('count', 42) count = cache.get('count', 0)
Deletes 'username' from cache. Getting it after returns
None.Django
cache.delete('username') user = cache.get('username')
Sample Program
This example shows saving a greeting message in cache, retrieving it, deleting it, and then trying to get it again with a default message.
Django
from django.core.cache import cache # Save a value in cache for 10 seconds cache.set('greeting', 'Hello, world!', timeout=10) # Retrieve the cached value message = cache.get('greeting') print(message) # Delete the cached value cache.delete('greeting') # Try to get it again message_after_delete = cache.get('greeting', 'No message found') print(message_after_delete)
OutputSuccess
Important Notes
Cache keys should be unique and descriptive to avoid conflicts.
Timeout controls how long data stays in cache; after that, it is removed automatically.
Use cache wisely to avoid stale data or memory overuse.
Summary
The low-level cache API stores and retrieves data fast in Django.
Use cache.set to save, cache.get to read, and cache.delete to remove data.
It helps speed up your app by avoiding repeated work.