【问题标题】:django - list of lists in templatedjango - 模板中的列表列表
【发布时间】:2013-03-29 13:10:54
【问题描述】:

我正在尝试呈现使用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='')

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

【问题讨论】:

  • 只是好奇,你为什么要压缩?为什么不使用关系?
  • @Bibhas,你的意思是:all_locations = Location.objects.all() 和模板中的{% for loc in all_locations %} {% for img in loc.locs_image.all %}{{img.img.name}} {% endfor %} {% endfor %}
  • 是的。为什么不呢?如果你只想要一个项目,你可以在模板中使用slice 标签。

标签: python django django-templates


【解决方案1】:

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

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

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

{% endfor %}

How to render a context

【讨论】:

  • 你能展示你的渲染函数和你要定位的模板部分吗?
【解决方案2】:

我认为你应该看看django-multiforloop

【讨论】:

    【解决方案3】:

    您还可以根据类型处理模板中的列表元素(使用 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 2014-06-18
      • 2011-05-22
      • 2014-11-16
      相关资源
      最近更新 更多