只有在之前没有插入时才插入分隔符

Insert separator only if didn’t insert one before

我有一个模板变量 product_list,它是 QuerySetProduct 个对象; Product 个对象又具有 Track 个对象的一对多字段(当然是从 Track 反向映射),它可能为空。我想创建一个 Track 的列表,按 Product 分组,如下所示:

{% for product in product_list %}
    {% if this is not the first product with tracks %}
        <li class="separator"></li>
    {% endif %}

    {% for track in product.tracks %}
        <li>{{track}}</li>
    {% endfor %}
{% endfor %}

问题是,if this is not the first product with tracks应该怎么写?我试过 ifchanged product 但它甚至在第一次迭代时也插入了一个分隔符(因为它从 "" 变为 "someproduct")。 forloop.counter这里也不能用,因为前两个产品可能没有曲目。

一种解决方法是将 product_list 更改为 track_list,如下所示:

track_list = Track.objects.order_by('product__name')

所以我确实可以使用ifchanged。这对我来说是可行的,但我仍然对第一种方法的解决方案感兴趣。

你应该写条件。看起来很简单,也许不是你要的。

{% for product in product_list %}
    {% if not forloop.first and product.tracks %}
        <li class="separator"></li>
    {% endif %}

    {% for track in product.tracks %}
        <li>{{track}}</li>
    {% endfor %}
{% endfor %}

如果这不是您的解决方案,我建议您在视图中处理数据并发送准备好解析到模板,更简单。

{% for product in product_list %}
    {% if product.should_have_separator %}
        <li class="separator"></li>
    {% endif %}

    {% for track in product.tracks %}
        <li>{{track}}</li>
    {% endfor %}
{% endfor %}

在您看来,动态附加 should_have_separator 字段到产品应该有它:

product_list = Product.objects.....
is_the_first_product = True
for product in product_list:
    is_the_first_product_with_tracks = ( is_the_first_product 
                                        and bool( product.tracks ) )
    product.should_have_separator = not is_the_first_product_with_tracks
    is_the_first_product = False