如何使用Django ORM按文章计数获取所有文章的年份列表 [英] How to use Django ORM to get a list by year of all articles with an article count

查看:236
本文介绍了如何使用Django ORM按文章计数获取所有文章的年份列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用django ORM在所有文章的年份之前得到一个列表,其中包含一些文章,例如:



2010(5篇文章)

2009(4篇文章)

2008(9篇)



我尝试过的东西,如:



archive = Articles.objects.dates('created','year')。annotate(archive_count = Count('created'))



或:



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



或:



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



最后一个给了我正确的数字,但没有给我任何一年的价值,其他的混合没有或archive_count被设置对于每一行,为1。



任何想法,我会出错?

解决方案>

这是一种查询方式:

  Article.objects.extra(选择= { '年': 的strftime( '%% Y',创建)})。值( '年')ORDER_BY()注释(Count('id'))

请注意,您必须替换 strftime('%% Y',created)根据你的数据库(我使用sqlite)。


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

这篇关于如何使用Django ORM按文章计数获取所有文章的年份列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆