Nested Archive Link in Django

Let’s say you have a blog in Django and want to have archive link on the sidebar. The link of course is matched to the date of your posts. You cant have a ‘June 2010′ link if you never post on that month. This post will try to handle that, creating nested archive link yearly and monthly.

data = Post.objects.all()

Here you got a QuerySet containing all your posts. Next is getting distinct year/month values from your posts grouped by year. To do this you need a set of distinct years.

year = ([d.year for d in data.dates('publish', 'year', order='DESC')])

Now that you have it, you can get what you want. I originally used a dict to contain the result,

result = dict([(y, data.filter(publish__year=y).dates('publish', 'month', order='DESC')) for y in year])

but dict is not sortable (you can sort the keys on an external data structure, though), so I put it on a nested tuple.

result = ([([y, data.filter(publish__year=y).dates('publish', 'month', order='DESC')]) for y in year])

I use date_based generic view, so I put this on extra_context for easier inclusion. All that remains is viewing it on the template with filters and stuff. I am pretty new with this, any better suggestions?

Tags: , ,

Leave a Reply