Django 将元组字典传递给模板
Django passing dictionary of tuples to template
如果我做一组这样的代码...
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(我知道我需要继续前进,所以不要在你的回答中提及它)。
为什么不直接将 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 %}
像这个例子:
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 %}
如果我做一组这样的代码...
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(我知道我需要继续前进,所以不要在你的回答中提及它)。
为什么不直接将 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 %}
像这个例子:
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 %}