Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Django ORM to get a list by year of all articles with an article count

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?

like image 919
Kevin Avatar asked Feb 27 '23 01:02

Kevin


1 Answers

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).

like image 88
OmerGertel Avatar answered Apr 06 '23 03:04

OmerGertel