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 - 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 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.