我从db获得了2个查询集:
all_locations = Locations.objects.all()[:5]
rating = Rating.objects.all()[:5]
return render_to_response('index.html',{'all':all_locations,'rating':rating},context_instance=RequestContext(request))
但我被困在这里,不知道如何在一个循环中循环这两个查询集。这是错误的:
{% if all and rating %}
{% for every in all and rating %}
{{every.locationname}}, {{every.rating_score}}
{% endfor %}
{% endif %}
答案 0 :(得分:5)
您可以尝试zip(all_locations, rating)
。它将生成一个元组列表。然后你可以成对迭代它们。这是一个例子:(demo)
all_locations = ['ca','ny','fl']
ratings = ['best','great','good']
for (l,r) in zip(all_locations,ratings):
print l+':'+r
输出
ca:best
ny:great
fl:good
答案 1 :(得分:2)
我也遇到了这个问题。现在,我已修复它。 我正在使用
new=tuple(zip(queryset1,queryset2))
return render(request, 'template.html', {"n": new}).
在view.py中。
在template.html中,我使用以下三个句子。
{% for i in n %}
{% for j in i|slice:"0:1" %}
......operate queryset1
{% endfor %}
{% for z in i|slice:"1:2" %}
.....operate queryset2
{% endfor %}
{% endfor %}
It seems this method will fulfill your needs.
答案 2 :(得分:1)
这可能有效:
{% with rating|length as range %}
{% for _ in range %}
{{ rating[forloop.counter] }}
{{ location[forloop.counter] }}
{% endfor %}
{% endwith %}
我不确定rating|length
是否会胜任该工作......您可能需要添加rating|length|times' with
次`过滤器定义为:
@register.filter(name='times')
def times(number):
return range(number)