views:

61

answers:

3

I have a list of values I want to display in a template of django.

The list is more or less like this:

199801 string1
199802 string2
199904 string3
200003 string4
200011 string5

where the first column is a date in the form YYYYMM and the second is a generic string

the list is ordered by date desc

What I want to create is a list of stringx grouped by year something like this:

1998 string1, string2
1999 string3
2000 string4, string5

I gave a look to the documentation and I think the only thing I need is a way to create a variable where to store the "last year" I printed, so I can do something like:

if current_value.year != last_year
     #create a new row with the new year and the string
else
     #append the current string to the previous one

I think the only way I found is to write a custom templatetag and let it store the variable and the value... but before starting to write code I would like to know if there is a simpler way!

+4  A: 

Always do such thing in view, template system is not designed for such operations. Furthermore, it would be much harder to achieve this - the best idea that comes to my mind, is to create a filter. That, however, would be crazy - you would create a very specific filter just for one use. It's very easy to achieve in view:

last = None
result = []
for year, value in tuples:
    if year[0:4] == last:
        result[-1].append(value)
    else:
        result.append([value])
        last = year[0:4]
gruszczy
+2  A: 

using itertools groupby

l = [
    (199801, 'string1'),
    (199802, 'string2'),
    (199904, 'string3'),
    (200003, 'string4'),
    (200011, 'string5'),
]

from itertools import groupby
iterator = groupby(l, key=lambda item: str(item[0])[:4])

for year, str_list in iterator:
    print year, list(str_list)

output

1998 [(199801, 'string1'), (199802, 'string2')]
1999 [(199904, 'string3')]
2000 [(200003, 'string4'), (200011, 'string5')]
Ashok
Wow, this groupby iterator is great :-)
gruszczy
A: 

You can't create a variable in a view, by design.

However the ifchanged tag probably does what you want:

{% for val in values %}
  {% ifchanged val.0 %} {{val.0}} {% endifchanged %}
  {{ val.1 }}
{% endfor %}
Daniel Roseman