使用 Django 从字典列表中生成多个 row/column table

Generate a multiple row/column table with Django from a list of dictionaries

我有这个列表,它由来自 Django 查询的多个词典组成:

它是音乐学校每个课程中多种乐器的统计数据的汇总。

[{'count': 13, 'session': 1, 'instrument': u'Piano'}, {'count': 4, 'session': 1, 'instrument': u'Cello'}, {'count': 2, 'session': 1, 'instrument': u'Violin'}, {'count': 14, 'session': 2, 'instrument': u'Piano'}, {'count': 1, 'session': 4, 'instrument': u'Cello'}]

我知道总是有 4 个会话但有 n 个仪器,我如何循环制作一个具有 4 列和 n 行的 table?

我试过的几乎输出我想要的(我的模板):

        <table class="table">
        <thead>
        <tr>
            <th>Session 1</th>
            <th>Session 2</th>
            <th>Session 3</th>
            <th>Session 4</th>
        </tr>
        </thead>
        {% for stat in stats_instrument %}
                {% if stat.session == 1 %}
                <tr><td>{{ stat.instrument }} {{ stat.count }}</td></tr>
                {% endif %}
        {% endfor %}
        {% for stat in stats_instrument %}
                {% if stat.session == 2 %}
                <tr><td></td><td>{{ stat.instrument }} {{ stat.count }}</td></tr>
                {% endif %}
        {% endfor %}
     ...
    </table>

实际输出为:

|Session 1| Session 2| Session 3| Session 4|
|Piano 13 |
|Cello 4  |
|Violin 2 |
|         | Piano 14 |
|         |          |           | Cello 1 |

我想要的更像是:

|Session 1| Session 2| Session 3| Session 4|
|Piano 13 | Piano 14 |          | Cello 1  |
|Cello 4  |
|Violin 2 |

我看到了 3 个问题。

  1. 每一节的乐器都不一样,所以钢琴可以在第 1-2-3 节教授。
  2. 会话的乐器数量不同,会话 1 可以有大约 5 个乐器,会话 3 可以有大约 10 个乐器。
  3. 我正在循环多次相同的数据,但似乎效率不高。

我应该制作 4 tables 并放置类似内联块的东西吗?

您可以先在视图中排序 table,然后将简单的排序列表提供给模板。

首先按会话编号对它们进行分组

sessions = [{'count': 13, 'session': 1, 'instrument': u'Piano'}, {'count': 4, 'session': 1, 'instrument': u'Cello'}, {'count': 2, 'session': 1, 'instrument': u'Violin'}, {'count': 14, 'session': 2, 'instrument': u'Piano'}, {'count': 1, 'session': 4, 'instrument': u'Cello'}]

values = set(map(lambda x:x['session'], sessions))
grouped_sessions = [[y for y in sessions if y['session']==x] for x in values]

那么你应该有这样的东西:

[[{'count': 13, 'session': 1, 'instrument': u'Piano'}, {'count': 4, 'session': 1, 'instrument': u'Cello'}, {'count': 2, 'session': 1, 'instrument': u'Violin'}],[{'count': 14, 'session': 2, 'instrument': u'Piano'}],[{'count': 1, 'session': 4, 'instrument': u'Cello'}]]

现在在您的模板中,在 for 循环中执行一个 for 循环,例如:

<table><thead>...</thead><tbody>
<tr>
{% for g in grouped_sessions %}
    <td><table>
    {% for s in g %}
     <tr><td>{{s.instrument}} {{s.count}}</td></tr>
    {% endfor %}
    </table></td>
{% endfor %}
</tr>

这将创建许多嵌套的 table,但在视觉上它确实起作用了。

希望对您有所帮助。