django - 模板中的列表列表

时间:2013-03-29 13:10:54

标签: python django django-templates

我正在尝试使用zip()压缩列表。

list_of_list = zip(location,rating,images)

我想将此list_of_list呈现给模板,并且只想显示每个位置的第一张图片。

我的位置和图像模型是:

class Location(models.Model):
  locationname = models.CharField

class Image(models.Model):
  of_location = ForeignKey(Location,related_name="locs_image")
  img = models.ImageField(upload_to=".",default='')

这是压缩列表。如何仅访问模板中每个位置的第一张图像?

enter image description here

3 个答案:

答案 0 :(得分:3)

list_of_lists传递给RequestContext。然后,您可以在模板中引用images列表的第一个索引:

{% for location, rating, images in list_of_lists %}

...
<img>{{ images.0 }}</img>
...

{% endfor %}

How to render a context

答案 1 :(得分:1)

我想你应该看看django-multiforloop

答案 2 :(得分:0)

您也可以根据类型(使用Django 1.11)处理模板中的列表元素。

所以如果你有你描述的观点:

# view.py
# ...
list_of_lists = zip(location,rating,images)
context['list_of_lists'] = list_of_lists
# ...

您需要做的只是在模板中创建标签以确定元素的类型

# tags.py
from django import template
register = template.Library()
@register.filter
def get_type(value):
    return type(value).__name__

然后你可以检测列表元素的内容类型,如果列表元素本身是一个列表,只显示第一个元素

{% load tags %}
{# ...other things #}
<thead>
  <tr>
    <th>locationname</th>
    <th>rating</th>
    <th>images</th>
  </tr>
</thead>
<tbody>
  <tr>
    {% for a_list in list_of_lists %}
    {% for an_el in a_list %}
    <td>
        {# if it is a list only take the first element #}
        {% if an_el|get_type == 'list' %}
        {{ an_el.0 }}
        {% else %}
        {{ an_el }}
        {% endif %}
    </td>
    {% endfor %}
  </tr>
  % endfor %}
</tbody>