XenoChrist XenoChrist - 3 months ago 13
Python Question

Using zipped queryset many times in template

I have a model that is only a string :

class Data(models.Model):
string = models.CharField(max_length=200);


There are 2 registered instances of the model in my database.

It is rendered by this view, which zips the queryset which another list:

def index(request):
data = Data.objects.all();
data2 = [];
for x in data:
data2.append(0);
return render(request, 'testApp/index.html', {"data": zip(data, data2)})


and here's the template code:

{% for element, e in data %}
{{ element.string }} {{ e }} <br/>
{% endfor %}

{% for element, e in data %}
{{ element.string }} {{ e }} <br/>
{% endfor %}


This template iterates over the data twice, printing out the elements in the zipped list.

Here's my output:

hello there 0
i am a string 0


I am expecting 4 lines of output, because the 2 instances are looped over twice. However it's only printing them out once. What am I doing wrong?

Answer

In Pythno 3, zip will give you an iterator, meaning it will be consumed on the first loop and therefore not print anything on the second loop.

You can fix this by casting the iterator to a list, replacing zip(data, data2) with list(zip(data, data2)).