About Getting or Setting a Cache Value

Use the cache.get_or_set() to get a cached value if it exists or create and cache a value if it doesn't:

from django.core.cache import cache

def get_user_data(user):
    key = f"user_data:{user.pk}"
    return cache.get_or_set(
        key, 
        lambda: expensive_query(user), 
        timeout=300,
    )

Tips and Tricks Programming Optimization Django 6.x Django 5.2 Django 4.2 Memcached Redis Cache