我需要在django模板中进行数据透视(行列转置),我很确定ORM无法处理它.是否有诸如regroup之类的内置模板标签,它们可以处理数据透视.
以下正是我所需要的?
select * from exams;
+------+------+------+-------+
| pkey | name | exam | score |
+------+------+------+-------+
| 1 | Bob | 1 | 75 |
| 2 | Bob | 2 | 77 |
| 3 | Bob | 3 | 78 |
| 4 | Bob | 4 | 80 |
| 5 | Sue | 1 | 90 |
| 6 | Sue | 2 | 97 |
| 7 | Sue | 3 | 98 |
| 8 | Sue | 4 | 99 |
+------+------+------+-------+
列出如下
+------+-------+-------+-------+-------+
| name | exam1 | exam2 | exam3 | exam4 |
+------+-------+-------+-------+-------+
| Bob | 75 | 77 | 78 | 80 |
| Sue | 90 | 97 | 98 | 99 |
+------+-------+-------+-------+-------+
解决方法:
这个怎么样?
在您的views.py中…
exams = Exam.objects.all()
transposed = {}
for exam in exams:
transposed.setdefault(exam['name'], {}).update(
{'exam%s' % exam['exam']: exam['score']})
在您的模板中…
<table>
<tr><th>name</th> ... </tr>
{% for name, scores in transposed.items %}
<tr><td>name</td><td>scores.exam1</td><td>scores.exam2</td>
<td>scores.exam3</td><td>scores.exam4</td></tr>
{% endfor %}
</table>