To get the default value if the key does not exit, you can specify the second parameter:
cache.get('key', 'default')
cache.get() can take a default argument. This indicates what value should be returned if the object does not exist in the cache.
To keep the default value in the cache, if the key does not exist, you can provide a custom cache server . For instance. this extends the db cache backend (but works with others):
from django.core.cache.backends import db class CustomCache(db.CacheClass): def get(self, key, default=None): result = super(CustomCache, self).get(key, default) if result == default: self.add(key, default) return default return result
But I do not think this adds any value.
Update:
In response to a comment on another post: Yes compares the default value with the return value, and if both are equal, the value is added to the cache. But cache.add sets only a new value if the key is not (unlike cache.set , which is always overridden):
To add a key only if it does not already exist , use the add() method. It accepts the same parameters as set() , but will not try to update the cache if the specified key is already present.
source share