I am using view caching for a django project.
It says the cache uses the URL as the key, so I\'m wondering how to clear the cache of one of the keys if a user update
There's a trick that might work for this. The cache_page
decorator takes an optional argument for key_prefix
. It's supposed to be used when you have, say, multiple sites on a single cache. Here's what the docs say:
CACHE_MIDDLEWARE_KEY_PREFIX
– If the cache is shared across multiple sites using the same Django installation, set this to the name of the site, or some other string that is unique to this Django instance, to prevent key collisions. Use an empty string if you don’t care.
But if you don't have multiple sites, you can abuse it thus:
cache_page(cache_length, key_prefx="20201215")
I used the date as the prefix so it's easy to rotate through new invalidation keys if you want. This should work nicely.
However! Please note that if you are using this trick, some caches (e.g., the DB cache, filesystem cache, and probably others) do not clean up expired entries except when they're accessed. If you use the trick above, you won't ever access the cache entry again and it'll linger until you clear it out. Probably doesn't matter, but worth considering.