你好,我是个新手程序员
def calculateMark(mobile_a, mobile_b):
mobiles_list = [mobile_a, mobile_b]
for mobile in mobiles_list:
dimension = TechSpecificationAdd.objects.filter(mobile_name = mobile).values(dimension)
body_material = TechSpecificationAdd.objects.filter(mobile_name = mobile).values(body_material)
weight = TechSpecificationAdd.objects.filter(mobile_name = mobile).values(weight)
tech_variables = {'dimension' : dimension, 'body_material' : body_material, 'weight' : weight}
return render_to_response('compare.html', tech_variables)
我有这样的东西,一个移动列表,从数据库中赋值,然后在字典中分配变量。我正在考虑在字典中迭代并在模板中显示值。但问题是,我必须制作模板,以便在一页中显示两个移动电话信息,以便进行比较。如何在模板中一次显示两个移动电话的信息?我认为模板总是会显示一部手机的信息。其实我被困在这里了,我不知道现在该怎么办。从一开始我就错了吗?我需要字典吗?如何迭代或分配在模板中显示的值。还是我在问一个愚蠢的问题?
发布于 2013-12-24 16:18:53
改进Simeon(假设是有效的urls.py
),
from django.shortcuts import render
def calculateMark(request, mobile_a, mobile_b):
mobiles_list = [mobile_a, mobile_b]
results = []
for mobile in mobiles_list:
record = TechSpecificationAdd.objects.filter(mobile_name=mobile).values('dimension', 'body_material', 'weight')
results += record
return render(request, 'compare.html', {'data': results})
任何注释:
request
作为第一个参数。{{ record.dimension }}
、{{ record.body_material }}
和{{ record.weight }}
都将成为list。这就是为什么我们不使用results.append(dict)
,而是使用results += record
来适当地呈现{{ record }}
。render_to_response
进行渲染需要RequestContext
,而Django提供了简化模板呈现的django.shortcuts.render
。发布于 2013-12-24 14:54:43
我想你打算:
def calculateMark(mobile_a, mobile_b):
mobiles_list = [mobile_a, mobile_b]
results = []
for mobile in mobiles_list:
dimension = TechSpecificationAdd.objects.filter(mobile_name = mobile).values(dimension)
body_material = TechSpecificationAdd.objects.filter(mobile_name = mobile).values(body_material)
weight = TechSpecificationAdd.objects.filter(mobile_name = mobile).values(weight)
results.append({'dimension' : dimension, 'body_material' : body_material, 'weight' : weight})
return render_to_response('compare.html', { 'data': results })
在模板中,您可以这样做:
{% for record in data %}
{{ record.dimension }}
{{ record.body_material }}
{{ record.weight }}
{% endfor %}
https://stackoverflow.com/questions/20767508
复制