在 Django 中使用 rowspan 进行分组并重新分组

Jam*_*een 2 html django html-table django-templates

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

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

Name            Amount
======================
A name          200
                300
                500
Another name    200
                30
                450
                15
Run Code Online (Sandbox Code Playgroud)

模型 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>
Run Code Online (Sandbox Code Playgroud)

s29*_*s29 5

像这样的事情——

<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>
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅regroupifchanged