Python Django在列表中的字典上迭代,并在模板中显示数据
你好,我是一个新手程序员Python Django在列表中的字典上迭代,并在模板中显示数据,python,django,dictionary,django-templates,django-views,Python,Django,Dictionary,Django Templates,Django Views,你好,我是一个新手程序员 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 = TechS
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)
我有这样的东西,一个移动设备列表,从数据库分配值,然后在字典中分配变量。我正在考虑迭代字典并在模板中显示值。
但问题是,我必须制作一个模板,在一个页面中显示两个手机信息,以便进行比较。如何在模板中一次显示两个手机信息?我认为模板将始终显示一个手机的信息。
其实我有点困在这里,我不知道现在该怎么办。
我从一开始就错了吗?我是否需要这本字典?如何迭代或分配要在模板中显示的值。还是我在问一个愚蠢的问题?我想你打算:
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 %}
改进Simeon(假设一个有效的url.py
)
任何注释:
- 视图函数必须将
作为第一个参数请求
- 过滤总是返回列表(甚至只返回结果1),因此
,{{record.dimension}}
,和{{record.body\u material}}
都将成为列表。这就是为什么我们不使用{{record.weight}}
,而是使用results.append(dict)
,这样results+=record
将得到适当的渲染{{record}}
- 使用
进行渲染需要render_to_response
,Django提供了RequestContext
以简化模板渲染Django.shortcuts.render
mobile\u a
,然后mobile\u b
(因为mobiles\u list=[mobile\u a,mobile\u b]
)你好,如果我对像record.weight=record.weight/100这样的单个项目做一些数学计算的话。然后,如果我按照你说的写这行,结果+=记录。可以吗?“results”变量在做了数学运算后会被项目的新值更新吗?没问题,阿里。只有当你问我关于django烦人的事时,你才是在烦我。
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})