Skip to content
Advertisement

Django iterate all values from zip

first I zip all my lists just like

 books= zip(ID, bookName, *detail)

but as you see the detail has not only one element, I can not sure the number of list of detail. And the number is variable.

Than loop over it in templates like:

   {% for ID, bookName, detail, in books %}
            <tr>
                <td>{{ ID}}</td>
                <td>{{ bookName }}</td>
                <td>{{ detail }} </td>
            </tr>
        {% endfor %}

As I can not confirm the number of detail, I got the error message like “Need 3 values to unpack in for loop; got 5. “

Is there any method to get the right loop times when the list is variable.

Advertisement

Answer

You can enumerate over the tuples, and then iterate over the elements, so:

{% for record in books %}
  <tr>
    {% for item in record %}
      <td>{{ item }}</td>
    {% endfor %}
  </tr>
{% endfor %}
Advertisement