Setting a low timeout means cached data expires quickly. This causes the cache to miss often and fetch fresh data from the database repeatedly.
Cache key versioning lets you keep multiple versions of cached data. Changing the version makes Django look for a new key, so old cache is ignored.
from django.db import models from django.core.cache import cache from django.db.models.signals import post_save from django.dispatch import receiver class Product(models.Model): name = models.CharField(max_length=100) @receiver(post_save, sender=Product) def clear_product_cache(sender, instance, **kwargs): cache_key = f'product_{instance.pk}' cache.delete(cache_key) # Assume cache initially has {'product_1': 'Old Data'} product = Product(pk=1, name='New Name') product.save()
The post_save signal deletes the cache key for the saved product. So after saving, the cache entry is removed and returns None on get.
The correct method to remove a cache entry by key is cache.delete(key). Other methods do not exist in Django's cache API.
Django cache does not auto-update on model changes. You must manually delete or update cache keys after saving models to avoid stale data.
