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

时间:2014-09-23 15:07:34

标签: html django django-templates html-table

我在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>

1 个答案:

答案 0 :(得分:1)

像这样 -

<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

相关问题