query output formting in django template

By : sush
Source: Stackoverflow.com
Question!

I am trying to output the query in below table format in template

RAW.objects.filter(at_date__year='2011',at_date__month='02').values('user','attend').order_by().annotate(total=Count('attend'))

output from the query

[{'user': u'sushanth', 'total': 13, 'attend': u'P'}, {'user': u'sushanthreddy', 'total': 2, 'attend': u'A'}, {'user': u'ram', 'total': 5, 'attend': u'P'}, {'user': u'ram', 'total': 2, 'at_attend': u'PL'}]

here i want to make user as distinct in template ,attend as distinct header format and total down to respective header .

    user           P     A   PL

   sushanth        13    2   0
     ram           5     0   2

Can any help on this ?

By : sush


Answers

When you use a values clause, Django will send a DISTINCT phrase in SQL based on the values you're asking for. So, you're already getting only distinct combinations of "user" and "attend".

How big is this output likely to be? If you're looking at just a couple hundred rows, I would suggest simply iterating over your dictionaries in Python and creating a rollup. If you're looking at more than that, then there are a few options. Likely the one I would recommend would be to create a rollup model/table that is populated using post_save signals, that has the P, A, and PL information for each user, and where user is unique. Then you simply query the rollup table and spit out your data.

Basically you make a table that looks almost exactly like your output: four columns (not counting the primary key, of course). Then, every time a record in your current table is saved, it writes the appropriate number to the correct column in the rollup table.



This video can help you solving your question :)
By: admin