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 |
+------+-------+-------+-------+-------+
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With