0
0
DjangoHow-ToBeginner · 3 min read

How to Use Low Level Cache API in Django for Fast Data Access

Use Django's low level cache API by importing cache from django.core.cache. You can store data with cache.set(key, value, timeout), retrieve it with cache.get(key), and delete it with cache.delete(key). This API helps speed up your app by caching expensive computations or database queries.
📐

Syntax

The low level cache API provides simple methods to interact with the cache backend.

  • cache.set(key, value, timeout=None): Stores value under key for timeout seconds (default is the default cache timeout).
  • cache.get(key, default=None): Retrieves the value for key, or default if not found.
  • cache.delete(key): Removes the cached value for key.
  • cache.clear(): Clears all cache entries.
python
from django.core.cache import cache

# Store data in cache
cache.set('my_key', 'my_value', timeout=300)  # cache for 5 minutes

# Retrieve data from cache
value = cache.get('my_key')  # returns 'my_value' or None if expired

# Delete data from cache
cache.delete('my_key')

# Clear all cache
cache.clear()
💻

Example

This example shows how to cache a computed value and retrieve it later to avoid repeating expensive operations.

python
from django.core.cache import cache
import time

def expensive_computation():
    time.sleep(2)  # simulate slow operation
    return 'result'

# Try to get cached result
result = cache.get('expensive_key')
if result is None:
    result = expensive_computation()
    cache.set('expensive_key', result, timeout=60)  # cache for 1 minute

print('Cached result:', result)
Output
Cached result: result
⚠️

Common Pitfalls

Common mistakes when using Django's low level cache API include:

  • Not setting a timeout, which may cause cached data to persist longer than intended.
  • Using non-string keys or values that are not serializable by the cache backend.
  • Assuming cache is always available; cache backend misconfiguration can cause failures.
  • Not handling None returns from cache.get() properly.
python
from django.core.cache import cache

# Wrong: Using a list as a key (keys must be strings)
# cache.set(['list_key'], 'value')  # This will raise an error

# Right: Use string keys
cache.set('list_key', 'value')

# Wrong: Not checking if cache.get returns None
value = cache.get('missing_key')
if value is not None:
    print(value.upper())  # Safe to call upper()
else:
    print('Value not found in cache')

# Right: Provide default or check
value = cache.get('missing_key', '')
print(value.upper())
📊

Quick Reference

Here is a quick cheat sheet for Django's low level cache API methods:

MethodDescriptionParameters
cache.set(key, value, timeout=None)Store value under keykey: str, value: any serializable, timeout: seconds
cache.get(key, default=None)Retrieve value by keykey: str, default: any
cache.delete(key)Remove value by keykey: str
cache.clear()Clear all cacheNo parameters

Key Takeaways

Import and use cache from django.core.cache for low level caching.
Always use string keys and serializable values for cache storage.
Set appropriate timeout to control cache expiration.
Check for None when retrieving cache to avoid errors.
Use caching to speed up expensive or repeated operations in your app.