Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django template - for loop over 2 querysets

I am getting 2 querysets from db:

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))

But I am stuck here, not knowing how to loop over these 2 querysets in one loop. this is being wrong:

{% if all and rating %}
  {% for every in all and rating  %}
         {{every.locationname}}, {{every.rating_score}}
  {% endfor %}
{% endif %}
like image 643
doniyor Avatar asked Sep 03 '25 07:09

doniyor


1 Answers

You can try zip(all_locations, rating). It will produce a list of tuples. Then you can iterate over them in pairs. Here is an example: (demo)

all_locations = ['ca','ny','fl']
ratings = ['best','great','good']
for (l,r) in zip(all_locations,ratings): 
   print l+':'+r 

Outputs

ca:best
ny:great
fl:good
like image 195
Jason Sperske Avatar answered Sep 04 '25 20:09

Jason Sperske