Django循环 - 删除最后一个逗号

时间:2014-03-22 16:39:18

标签: django

我设置了以下循环,但是需要删除最后一项的逗号(它是为了循环2复制JSON数组)

{% for product_in_series in series.get_products %}{%spaceless%}
    {% with product_in_series.product as product %}
    {%if not forloop.first%}
            "<img src='{% version product.get_overview 'page_image' %}'>",
    {%endif%}
    {% endwith %}
{%endspaceless%}{% endfor %}

干杯, [R

3 个答案:

答案 0 :(得分:14)

这个怎么样?

{% for product_in_series in series.get_products %}{%spaceless%}
    {% with product_in_series.product as product %}
    {%if not forloop.first%}
        "<img src='{% version product.get_overview 'page_image' %}'>"
        {%if not forloop.last%},{%endif%}
    {%endif%}
    {% endwith %}
{%endspaceless%}{% endfor %}

答案 1 :(得分:1)

{{ forloop.last|yesno:",&#44;"|safe }}

&#44; - 是一个逗号

答案 2 :(得分:1)

以上都不适合我。 像Django 3.0一样,正确的语法也是如此

 {% with querythisandthat as A %}
   {% for  u in A %}  {{ u.interesting_stuff }} 
      {% if u == A.last %} . {% else %} ; {% endif %}
   {% endfor %}
 {% endwith %}

原因是A.last不是True / False,但它是查询集的最后一个元素

https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.first