上下文处理器,缓存

时间:2013-08-19 08:56:52

标签: django caching

我有一个'工作'模型,有三个主要类别绘图,动作,网页。我试图在自定义上下文处理器中进行缓存:

#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}

比我根据类别......

在模板中使用WORKS

这是一种好的或不必要的做法吗?

1 个答案:

答案 0 :(得分:1)

它有效并且不是不必要的练习,拥有良好的缓存是关键但是我有点困惑为什么你像你一样循环Work QuerySet。

这不适合你:

#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}

注意:category__root__slug='drawing'只是概念上的,因为您需要将其替换为正确的模型结构。如果你得到缓存未命中,你也永远不会将work_types放回缓存中,这也是你应该查看的内容。