【问题标题】:Grouping with rowspan and regroup in Django在 Django 中使用 rowpan 进行分组和重新分组
【发布时间】:2014-11-17 20:44:09
【问题描述】:

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

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

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

模型 B 对模型 A 有一个外键,所以我需要打印模型 B 的所有对象并按外键分组。

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

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

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

【问题讨论】:

  • 我已经编辑了我的问题

标签: html django django-templates html-table


【解决方案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

【讨论】:

    猜你喜欢
    • 2019-07-04
    • 2017-12-09
    • 2012-11-04
    • 2016-10-08
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-29
    • 2012-05-22
    相关资源
    最近更新 更多