Reputation: 15464
I need to do pivoting(row column transpose) in django template , i am pretty sure ORM cannot handle it . Is there any built in template tags like regroup
, which can take care of pivot.
Below is exactly what i need?
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 |
+------+------+------+-------+
to be listed as below
+------+-------+-------+-------+-------+
| name | exam1 | exam2 | exam3 | exam4 |
+------+-------+-------+-------+-------+
| Bob | 75 | 77 | 78 | 80 |
| Sue | 90 | 97 | 98 | 99 |
+------+-------+-------+-------+-------+
Upvotes: 4
Views: 3476
Reputation: 15793
Have you considered using something like pandas? It provides a DataFrame object that gives you pivot functionality in python. You could use it I views or in models depending on your needs. For a quick example, try looking at this question
Upvotes: 1
Reputation: 3158
How about this?
In your views.py ...
exams = Exam.objects.all()
transposed = {}
for exam in exams:
transposed.setdefault(exam['name'], {}).update(
{'exam%s' % exam['exam']: exam['score']})
In your template ...
<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>
Upvotes: 3