I'm trying to use Django LocMemCacheto store a few simple values, but I'm not sure how to initialize the cache when starting Django. Django 1.7 comes with Applications , allowing you to run some code in AppConfig.ready(), this place is ideal for initializing the cache, but according to the Django 1.7 Documentation:
"... Although you can access the model classes as described above by interacting with the database in your finished () implementation.
So, let's say I want to save some database queries from my model:
x = MyModel.objects.count()
y = MyModel.(a really expensive query)
How and when should I initialize the cache? Is there a recommended “best practice” for this? Currently, I just added to the application cache.py, but I'm not sure my code once gets into the database (i.e. the first request) and then uses the cached value before (the following requests).
from django.core.cache import caches
from .models import MyModel
class Cache(object):
def __init__(self):
self.__count = MyModel.objects.count()
self.cache = caches['cache-storage']
@property
def total_count(self):
return self.cache.get('total_count', self.__count)
Then I use the cached values as follows:
from .cache import Cache
cache = Cache()
...
(some view)
counter = cache.total_count
source
share