Django TEMPLATE_CONTEXT_PROCESSORS被称为太多次 [英] Django TEMPLATE_CONTEXT_PROCESSORS are being called too many times

查看:252
本文介绍了Django TEMPLATE_CONTEXT_PROCESSORS被称为太多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在所有页面中显示一些统计数字,所以我决定使用上下文处理器。但是我只是想出我的功能被称为每页加载2到7次。我在函数中做了4个查询,所以我的表现非常糟糕。每页加载最多可能需要28(4 * 7)个查询...

I need show some statistic numbers in all pages, so I decided to use context processors. But I just figured out that my function is being called 2 to 7 times every page load. I am doing 4 queries inside the function, so I am getting a very bad performance. Every page load it can take up to 28 (4*7) queries...

我想知道为什么会发生这种情况,我该怎么做才能避免。

I would like to know why this is happening and what can I do to avoid it.

settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.request',
    'django.contrib.messages.context_processors.messages',
    'django.core.context_processors.static',
    'core.views.numbers',
)

views.py

def numeros(request):
      ...
    a=table1.objects.count()
    b=table2.objects.count()
    c=table3.objects.count()
    d=table4.objects.count()
     ...
    return {'a': a,
            'b': b,
            'c': c,
            'd': d,
            'e': e,
            'f': f,
            'g': g,
            'h': h
    }

[UPDATED - 谢谢]
@okm和@catherine pro给出了很好的补充说明。两个都是正确的,正如@okm所说,上下文处理器被称为几次,因为我使用RequestContext多一次。

[UPDATED - Thanks] @okm and @catherine provided very good and complementary explanation. Both were correct, as @okm said, the context processors was being called several time because I was using RequestContext more then once.

@catherine也是正确的。我们需要特别注意上下文处理器中的内容。我更改了我的代码,我只是在着陆页上显示统计数字。

@catherine also is correct. We need pay extra attention what we put in context processors. I changed my code and I am just displaying the statistic numbers in the landing page.

推荐答案

TEMPLATE_CONTEXT_PROCESSORS中的设置功能可以在所有页面中使用。但请注意,即使您没有调用它或使用它,仍然加载查询,因为它直接从设置调用。会导致性能不佳。只需使用上下文处理器,几乎在每个模板中使用它,如用户或其他不具有很多成本的参数。

Setting function in TEMPLATE_CONTEXT_PROCESSORS have the advantage to use it in all pages. But be aware that even if you did not call it or use it, still it loads the queries because it directly call from the settings. It will result to bad performance. Use only the context processor when you have to use it almost in every template like the user or other parameters that don't have a lot of cost.

这篇关于Django TEMPLATE_CONTEXT_PROCESSORS被称为太多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆