我从数据库中得到 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))
但我被困在这里,不知道如何在一个循环中遍历这 2 个查询集。这是错误的:
{% if all and rating %}
{% for every in all and rating %}
{{every.locationname}}, {{every.rating_score}}
{% endfor %}
{% endif %}
最佳答案
您可以尝试 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
关于python - django 模板 - 循环遍历 2 个查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15628574/