如果我制作了一组像这样的代码......
object_data = {}
object = Object.objects.all()
for o in object:
ratings = ObjectRating.objects.filter(recipe=r)
counter = 0
ratings_sum = 0
for s in ratings:
counter += 1
ratings_sum += s.rating
rating_average = ratings_sum / counter
object_data[`o.id`] = (o, rating_average,)
data = {
'search_by' : search_by,
'object' : object_data
}
如果我将数据字典传递给页面(render_to_response(page, data, context_instance=RequestContext(request))
),我如何从模板中的元组的两个部分获取数据。
这就是我认为我必须这样做的方式......
{% for o in object %}
<tr><td>{{ o.0.name }}</td><td>{{ o.0.description }}</td><td>{{ o.0.other_col }}</td><td>{{ o.0.another_col }}</td><td>{{ o.1 }}</td></tr>
{% endfor %}
这让我感到疯狂,任何见解都会有所帮助。这是Django 1.6(我知道我需要继续前进,所以在你的回答中不要提及)。
答案 0 :(得分:0)
为什么不将rating_average
作为属性添加到object
?
for o in object:
... # calculate rating average for this object
o.rating_average = ratings_sum / counter
data = {
'search_by' : search_by,
'object' : object
}
{% for o in object %}
<tr><td>{{ o.name }}</td>
<td>{{ o.description }}</td>
<td>{{ o.other_col }}</td>
<td>{{ o.another_col }}</td>
<td>{{ o.rating_average }}</td>
</tr>
{% endfor %}
答案 1 :(得分:0)
就像这个例子:
class HomeView(generic.TemplateView):
template_name = '_layouts/index.html'
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
mydict = {'wat': 'coo'}
context['mydict'] = mydict
return context
模板:
{% for key, value in mydict.items %}
{{ key }} : {{ value }}
{% endfor %}