【问题标题】:Need help in Django Templates(using forloops)在 Django 模板中需要帮助(使用 for 循环)
【发布时间】:2021-03-11 00:01:37
【问题描述】:

我有 3 个模型,即 Uses、Customer 和 Services。我有一个查询,其结果存储在变量 count 中。

这是查询

counts = Services.objects.filter(uses__customer=customer).annotate(times_used=Count('uses'))

每个 count[x].times_used 都有一个变量,x 范围从 0 到无穷大。

我在我的 html 中使用了一个 for 循环来获取我在视图中通过上下文传递的所有服务。 现在我需要为每个服务获取唯一的计数值。我该怎么做。

这是我的html代码

<table class='table table-bordered' id='dataTable' width='100%' cellspacing='0'>
    <thead class='bg-primary'>
        <tr class='text-white'>
            <th>Service-Id</th>
            <th>Service-name</th>
            <th>Count</th>
            <th>Price</th>
        </tr>
    </thead>

    <tbody class="text-dark">
        <tr>{% for service in services %}
            <td>{{ service.id }}</td>
            <td>{{ service.service_name }}</td>
            <td>#code for printing count[x],times_used#</td>
            <td>{{ service.price }}</td>
        </tr>{% endfor %}
    </tbody>
</table>

【问题讨论】:

  • 您想获取给定服务的索引吗?或者通过相对于服务的索引显示具有相应信息的另一个列表?
  • 我想显示另一个列表,其中包含与服务相关的索引的相应信息。

标签: python django django-templates


【解决方案1】:
{% for elem_1 in results_1 %}

    {{elem_1}}

    {% for elem_2 in results_2|index_filter:forloop.counter0 %}

    {{elem_2}}
       
    {% endfor %}
{% endfor %}

您可以在模板中的任何地方使用该结构。

您使用内置过滤器“index_filter”。

基本上,当 myvar 通过管道将| 传输到index_filter:forloop.counter0 时,该函数将调用 results_2 中索引 = forloop.counter0 的元素。这个后来的计数器是父 for 循环之一。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 2012-06-10
    • 2021-05-14
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 2021-08-25
    相关资源
    最近更新 更多