I've added a simple caching to my web application and when I delete or add new object the cache does not get refreshed after the peroid of time (2 minutes) that I've set.
It looks like it froze. When I restart my application then it gets refreshed.
I tried it on memached and locmemcache.
INDEX_LIST_CACHE_KEY = "index_list_cache_key"
class IndexView(BaseView):
queryset = Advert.objects.all().select_related('category', 'location')[:25]
template_name = "adverts/category_view.html"
def get_queryset(self):
queryset = cache.get(INDEX_LIST_CACHE_KEY)
if queryset is None:
queryset = self.queryset
cache.set(INDEX_LIST_CACHE_KEY, queryset, 2 * 60)
return queryset
Why caching behaves like that in this project?
Edit - settings.py:
for locmemcache
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'oglos-cache'
}
}
for memcached
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
解决方案
Because by slicing the queryset in the class definition, you've evaluated it then and there - at class definition time, ie when the server starts up. So the cache is being refreshed, but only with an old set of items. Don't do that slice at class level: do it when returning the results from get_queryset.