Decrease DB requests number from Django templates
I publish discount offers for my city. Offer models are passed to template ( ~15 offers per page)开发者_开发百科. Every offer has lot of items(every item has FK to it's offer), thus i have to make huge number of DB request from template.
{% for item in offer.1 %}
{{item.descr}}
{{item.start_date}}
{{item.price|floatformat}}
{%if not item.tax_included %}{%trans "Without taxes"%}{%endif%}
<a href="{{item.offer.wwwlink}}" >{%trans "Buy now!"%}</a> </div>
<div class="clear"></div>
{% endfor %}
So there are ~200-400 DB requests per page, that's abnormal i expect.
In django code it is possible to use select_related to prepopulate needed values, how can i decrease number of requests in template?
In the same way, surely. When you get the list of offers in the view, do select_related
there.
You can do usual - retrieve ALL variables in view in optimized way and then pass it to template. Template is not (and should not) be a place to do database magic.
Django is, however, not suited much for that; it's more common to cache heavily. For example, a lot of tags may do database hit...
精彩评论