ratata
ratata

Reputation: 1169

Context processors, caching

I have a 'work' model that have three main categories drawing, motion, web. I am trying to make caching inside custom context processor:

#custom context processor
works = cache.get(cache_key_works)
if not works:
    workList = Work.objects.filter(publish=1).order_by('-publish_from')
    works = {'drawings': [], 'webdesigns': []}
    for w in workList:
        s = w.category.get_root().slug_en
        if s == 'drawing':
            works['drawings'].append(w)
        elif s == 'web-design':
            works['webdesigns'].append(w)
return {'WORKS': works}

Than i use WORKS in the templates according to category...

Is this a good or unnecessary practise?

Upvotes: 0

Views: 847

Answers (1)

Henrik Andersson
Henrik Andersson

Reputation: 47212

It works and it's not unnecessary practice, having a good cache is key however I'm a bit confused as to why you're looping over the Work QuerySet as you do.

Wouldn't this work for you:

#custom context processor
works = cache.get(cache_key_works)
if not works:
    drawings = Work.objects.filter(publish=1, category__root__slug='drawing').order_by('-publish_from')
    web_designs = Work.objects.filter(publish=1, category__root__slug='web_designs').order_by('-publish_from')
    worktypes = {'drawings': drawings, 'web_designs': web_designs}

return {'work_types': work_types}

NOTE: The category__root__slug='drawing' is just conceptually since you need to replace it with your correct model structure. Also you're never putting the work_types back into the cache if you get a cache miss, which is something you should look over too.

Upvotes: 1

Related Questions