4

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 |
+------+-------+-------+-------+-------+
sumit
  • 15,003
  • 12
  • 69
  • 110
  • Django doesn't allow pivoting, and the last place you should do it is in templates (presentation layer) but better in the views for sure! Raw mysql query to compose that table and it should do it – Samuele Mattiuzzo May 21 '12 at 13:32
  • 'regroup' has a similar function, yet it is indeed used in templates! – Don May 21 '12 at 14:06

2 Answers2

3

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>  
jcfollower
  • 3,103
  • 19
  • 25
  • Also, choose a better variable than "transposed". That was just to help you see what I was doing. Maybe "student_scores". – jcfollower May 22 '12 at 13:43
1

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

Community
  • 1
  • 1
The Real Bill
  • 14,884
  • 8
  • 37
  • 39