获取Django模板中for循环中的第一个元素

时间:2017-03-20 14:02:18

标签: django django-templates django-views

模板:

Kadane's algorithm

查看

{% for code in group_codes %}
        *_{{ code.build }}_*<br />
        {% if test_info.test_type = 0 %}
            {{ code.pre_testing_fail }}/{{ code.pre_testing_total }} failed pre-test<br />
        {% else %}

        {% for shelf in final_shelf_info %}

        {{ shelf.build }} <br/>

           {% if shelf.build = code.build %}

            {{ mr_script_count_func }}/{{ code.script_total }} 
            <span>MR</span> failed during script<br />
            {{gw_script_count_func}}/{{ code.script_total }} 
            <span>GW</span> failed during script<br />
            {{ mr_post_count_func }}/{{ code.post_testing_total }} 
            MR failed during post-test<br/>
            {{ gw_post_count_func }}/{{ code.post_testing_total }}
             GW failed during post-test<br/>
             {% endif %}

        {% endfor %}


        <br/>
        <br/>
    {% endif %}
{% endfor %}

我想获得for循环中的第一个元素

 def final_shelf_info(self):
    shelves = self.bugs_stbs()
    shelfList = list()

    for shelf in shelves:
        shelfList.append(shelf.results_stb_id)

    final_info = ResultsStbs.objects.select_related(
        'build',
        'pre_testing_result',
        'script_result',
        'post_result',
    ).filter(
        results_stb_id__in=shelfList,
        tr_test_case_id=self.kwargs['trTestCaseID'],
    ).order_by(
        'pair_no','shelf_no',
    )

    for info in final_info:
        if info.stb_hw_info_ids:
            info.stb_type = info.stb_hw_info_ids.stb_hw_info.stb_type
        else:
            info.stb_type = None

    return final_info

并与其他数据进行比较。

如何获得第一个循环中的第一个元素。

第一个要素:Q004.01.55.01.55.19_9423

{{shelf [0] .build}}我试过这样,它没用。

for循环的输出:

{% for shelf in final_shelf_info %}

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:2)

{% for shelf in final_shelf_info %}
    {% if forloop.first %}
        Do something with {{ shelf }} since its the first item iterated
    {% endif %}
{% endfor %}

有关docs。{/ p>中{% for %}模板循环的更多信息

答案 1 :(得分:1)

你可以这样做:

        {% for t in things %}

                {% if forloop.first %}
                    // do something                            
                {% endif %}

                // do stuff

                {% if forloop.last or things.count == 1 %}
                    // do something
                {% endif %}

        {% endfor %}

Django documentation

提供了更多文档

答案 2 :(得分:0)

{% if final_shelf_info.0 == shelf %}

{% if final_shelf_info.first == shelf %}