I am trying use the django ORM to get a list by year of all my articles with an article count beside it, such as this:
2010 (5 articles)
2009 (4 articles)
2008 (9 articles)
I have tried things such as:
archive = Articles.objects.dates('created', 'year').annotate(archive_count=Count('created'))
or:
archive = Articles.objects.values('created').annotate(archive_count=Count('created'))
or:
archive = Articles.objects.values('created').aggregate(archive_count=Count('created'))
The last one gave me the right count but didn't give me any of the year values, the other ones give a mix of either nothing or archive_count being set to 1 for each row.
Any ideas where I am going wrong?
Here's a way to do it in one query:
Article.objects.extra(select={'year':"strftime('%%Y',created)"}).values('year').order_by().annotate(Count('id'))
Note that you'll have to replace strftime('%%Y',created)
according to your database (I was using sqlite).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With