gpt4 book ai didi

html - 使用 rowspan 分组并在 Django 中重新组合

转载 作者:行者123 更新时间:2023-11-28 01:41:09 24 4
gpt4 key购买 nike

我在 Django 中有一个多对一的关系:模型 A 和模型 B。

我需要输出一个表,其中对象按名称排序和分组

Name            Amount
======================
A name 200
300
500
Another name 200
30
450
15

模型 B 有模型 A 的外键,所以我需要打印所有模型 B 对象并按外键对它们进行分组。

我知道我可以使用 rowspan html 属性和 Django 中的重组过滤器来完成此操作,但我不确定如何编写模板。

通常我可以只创建输出所有对象,但我不想在每一行中都写上名字。所以我需要将它们分组。

<table>
<thead><tr><th>Name</th><th>Amount</th></tr></thead>
<tbody>
{% for obj in object_list %}
<tr>
<td>{{ obj.name }}</td>
<td>{{ obj.amount }}</td>
</tr>
{% endfor %}
</tbody>
</table>

最佳答案

像这样——

<table>
<thead><tr><th>Name</th><th>Amount</th></tr></thead>
<tbody>
{% regroup object_list by name as grouped %}
{% for group in grouped %}
{% for obj in group.list %}
<tr>
{% ifchanged %}<td rowspan="{{ group.list|length }}">{{ obj.name }}</td>{% endifchanged %}
<td>{{ obj.amount }}</td>
</tr>
{% endfor %}
{% endfor %}
</tbody>
</table>

有关更多信息,请参阅 regroupifchanged .

关于html - 使用 rowspan 分组并在 Django 中重新组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25998557/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com