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

白昼怎懂夜的黑 提交于 2019-12-04 10:09:08

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

I'm not sure if keeping database hits to a minimum is your chief goal. If so, there may be another way that I haven't considered. But at first glance, this looks like what you want:

archive={}
years = Article.objects.dates('created', 'year')
for year in years:
    archive[year.year] = Article.objects.filter(created__year=year.year).count()

Then you'll have a dictionary with {2010: 5, 2009: 4, 2008: 9}.

In an ideal world, you would be able to write:

archive = Articles.objects.values('created__year').annotate(archive_count=Count('created')).order_by()

to get your desired results. Unfortunately django doesn't support anything other than exact field names as an arguments to values()

archive = Articles.objects.values('created').aggregate(archive_count=Count('created'))

can't possibly work since values('created') gives you a dictionary of all unique values for 'created', which is composed of more than just 'year'.

If you really want to do this with a single ORM call, you'll have to use the extra function and write entirely custom SQL. Otherwise Justin's answer should work well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!