views:

34

answers:

2

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?

+1  A: 

In the same way, surely. When you get the list of offers in the view, do select_related there.

Daniel Roseman
but how? should i do - {% for item.select_related in offer.1 %} ?
Andrew
No - as I said, in the view. It would help if you show exactly how you're getting `offer` in the first place.
Daniel Roseman
A: 

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

Almad