Lucas Ou-Yang
Lucas Ou-Yang

Reputation: 5655

Confusion with caching with memcached and django

I am caching a bunch of queries for some models in my django project. It appears that the caching itself is working, but when I wanted to do a test by adding a new model object, I noticed that right after the model was created, the query listing was updated to include the new model, which should be incorrect because the cache timeout was set to 1 unix hour.

Shoulden't we have to wait 1 hour before seeing the new model? Here is the code:

def home(request, filterBy = 'all', sortBy = 'popularity'):
    if not cache.get('home' + filterBy + sortBy):
        models = Model.objects.with_rankings(filterBy, sortBy, request)
        cache.set('home' + filterBy + sortBy, models, 3600) # 1 hour
    else:
        models = cache.get('home' + filterBy + sortBy)

Thank you.

Upvotes: 0

Views: 292

Answers (1)

jasisz
jasisz

Reputation: 1298

Remember that cache.get(key) returns None not False or anything else if there is no value in cache. And you are not checking for it, you are just checking if returned value is true or is it not. Empty QuerySet is also false and probably it is your case.

It should be (also it is one cache get less):

def home(request, filterBy = 'all', sortBy = 'popularity'):
    models = cache.get('home' + filterBy + sortBy)
    if models is None:
        models = Model.objects.with_rankings(filterBy, sortBy, request)
        cache.set('home' + filterBy + sortBy, models, 3600) # 1 hour

Upvotes: 3

Related Questions