3

我从 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 %}
4

3 回答 3

5

你可以试试zip(all_locations, rating)。它将产生一个元组列表。然后你可以成对地迭代它们。这是一个例子:(演示

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
于 2013-03-26T03:38:01.827 回答
3

我也遇到过这个问题。现在我已经修好了。我所做的是使用

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.
于 2018-08-11T09:48:38.550 回答
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)
于 2013-03-26T03:37:18.987 回答