Well to get a default value if the key does not exits you can provide a second parameter:
cache.get('key', 'default')
cache.get()
can take a default argument. This specifies which value to return if the object doesn't exist in the cache.
To save the default value in cache if the key does not exist, you can provide your custom cache backend. E.g. this extends the db
cache backend (but works the same 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 don't think that this adds any value.
Update:
In response to the comment on the other post: Yes it compares the default value with the returned value and if both are equal, the value gets added to the cache. But cache.add
only sets the new value if the key is not already in the cache (contrast to cache.set
which always overrides):
To add a key only if it doesn't already exist, use the add()
method. It takes the same parameters as set()
, but it will not attempt to update the cache if the key specified is already present.