Django按月份注释分组 [英] Django annotate groupings by month

查看:148
本文介绍了Django按月份注释分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常基本的模型:

I have a very basic model:

class Link(models.Model):
    title = models.CharField(max_length=250, null=False)
    user = models.ForeignKey(User)
    url = models.CharField(max_length=250, blank=True, null=True)
    link_count = models.IntegerField(default=0)
    pub_date = models.DateField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

我可以使用以下方式创建按日期分组的所有条目的列表:

I can create a list of all the entries grouped by date using:

Link.objects.values('pub_date').order_by('-pub_date').annotate(dcount=Count('pub_date'))

自然会按天分组。但是我真的想做的是一个个月。有没有办法使用annotate()?

This will naturally group items by day. But what I really want to do is group by month. Is there anyway I can do this using annotate()?

非常感谢,

G

推荐答案

如果您使用PostgreSQL,以下内容可能会起作用:

If you're on PostgreSQL, the following might work:

from django.db.models import Count

Link.objects.extra(select={'month': 'extract( month from pub_date )'}).values('month').annotate(dcount=Count('pub_date'))

我不知道如何便携式提取是跨其他数据库。

I'm not sure how portable extract is across other databases.

这篇关于Django按月份注释分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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