我有一个视图,它从模型中获取两个对象,并返回由两个对象组成的上下文以及每个对象属性之间的差值列表。从在线查看,在Django模板中索引此列表的方法只是{{difference.0}},但它不适用于我的情况,我无法弄清楚原因。将列表打印到模板中的屏幕时,它只会打印一个空列表,这意味着我传递的列表为空。但是我已经在shell中测试了我的代码,它产生了我想要的列表。我错过了什么?
以下是我的观点:
def compare(request, champion1, champion2):
champion1_requested = get_object_or_404(Champion, name=champion1)
champion2_requested = get_object_or_404(Champion, name=champion2)
difference = []
list1 = Champion.objects.values_list('hp', 'hp5', 'hp5Plus').filter(name=champion1)
list2 = Champion.objects.values_list('hp', 'hp5', 'hp5Plus').filter(name=champion2)
for i in xrange(len(list1[0])):
#if isinstance(list1[i], (int, float, long, complex)):
difference.append(float(list1[0][i]))
context = {'champion1': champion1_requested,
'champion2': champion2_requested,
'difference': difference}
return render(request, 'ChampData/compare.html', context)
以下是我的模板的一部分:
{% extends 'ChampData/theme.html' %}
{% block container %}
<h1 style="text-align: center;">Champion Comparison</h1>
{{ difference }}
{{difference}}
{{ difference.0 }}
{{ difference.2 }}
{% if champion1 %}
{% if champion2 %}
<table class="table table-hover">
<tr><th>Name:</th><td>{{ champion1.name }}</td><td>{{ champion2.name }}</td></tr>
<tr><th>Style:</th><td>{{ champion1.style }}</td><td>{{ champion2.style }}</td></tr>
<tr><th>Health:</th><td>{{ champion1.hp }}</td><td>{{ champion2.hp }}</td><td>{{ difference.0 }}</td></tr>
<tr><th>Health per level:</th><td>{{ champion1.hpPlus }}</td><td>{{ champion2.hpPlus }}</td><td>{{ difference.1 }}</td></tr>
<tr><th>Health Regen per 5:</th><td>{{ champion1.hp5 }}</td><td>{{ champion2.hp5 }}</td><td>{{ difference.2 }}</td></tr>
<tr><th>Health Regen per 5 per level:</th><td>{{ champion1.hp5Plus }}</td><td>{{ champion2.hp5Plus}}</td></tr>
表格开头的'{{difference}}'只打印'[]','{{difference.0}}'不打印任何内容,但这是我在shell中测试它:
>>> list1 = Champion.objects.values_list('hp','hp5','hp5Plus').filter(name='Ahri')
>>> difference = []
>>> for i in xrange(len(list1[0])): difference.append(float(list1[0][i]))
...
>>> difference
[514.4, 6.505, 0.6]
所以,我不知道为什么它不会工作。任何帮助将不胜感激。