您好我是新手程序员
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)
我有这样的东西,一个移动列表,从数据库中分配值,然后在字典中分配变量。我正在考虑迭代字典并在模板中显示值。 但问题是我必须让模板在一个页面中显示两个手机信息以进行比较。如何在模板中一次显示两个手机信息?我认为模板总是会显示一个手机的信息。 其实我有点卡在这里,我不知道现在该做什么。 我从一开始就错了吗?我需要字典吗?如何迭代或分配值以在模板中显示。或者我问一个愚蠢的问题?
答案 0 :(得分:3)
改进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 }}
都将成为列表。这就是为什么我们使用results.append(dict)
代替results += record
,以便恰当地呈现{{ record }}
。render_to_response
进行渲染需要RequestContext
,Django提供django.shortcuts.render
来简化模板渲染。答案 1 :(得分:2)
我认为你打算这样做:
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 %}