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

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

问题描述

我正在尝试使用 django ORM 来获取我所有文章的年份列表,旁边还有文章计数,例如:

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 篇)
2009(4篇)
2008(9篇)

2010 (5 articles)
2009 (4 articles)
2008 (9 articles)

我尝试过诸如:

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

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').annotate(archive_count=Count('created'))

或:

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

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

最后一个给了我正确的计数,但没有给我任何年份值,其他的给我混合了没有或为每行设置为 1 的 archive_count.

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

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

Note that you'll have to replace strftime('%%Y',created) according to your database (I was using sqlite).

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

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