Nested Archive Link in Django
Wednesday, June 9th, 2010Let’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?
![[del.icio.us]](http://kusut.web.id/wp-content/plugins/bookmarkify/delicious.png)
![[Digg]](http://kusut.web.id/wp-content/plugins/bookmarkify/digg.png)
![[Facebook]](http://kusut.web.id/wp-content/plugins/bookmarkify/facebook.png)
![[Google]](http://kusut.web.id/wp-content/plugins/bookmarkify/google.png)
![[LinkedIn]](http://kusut.web.id/wp-content/plugins/bookmarkify/linkedin.png)
![[Reddit]](http://kusut.web.id/wp-content/plugins/bookmarkify/reddit.png)
![[Slashdot]](http://kusut.web.id/wp-content/plugins/bookmarkify/slashdot.png)
![[StumbleUpon]](http://kusut.web.id/wp-content/plugins/bookmarkify/stumbleupon.png)
![[Technorati]](http://kusut.web.id/wp-content/plugins/bookmarkify/technorati.png)
![[Twitter]](http://kusut.web.id/wp-content/plugins/bookmarkify/twitter.png)
![[Email]](http://kusut.web.id/wp-content/plugins/bookmarkify/email.png)