Django按月注释分组

giv*_*ivp 16 python django

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

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)
Run Code Online (Sandbox Code Playgroud)

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

Link.objects.values('pub_date').order_by('-pub_date').annotate(dcount=Count('pub_date'))
Run Code Online (Sandbox Code Playgroud)

这将自然地按日分组项目.但我真正想做的是按月分组.无论如何我可以使用annotate()来做到这一点吗?

非常感谢,

G

ars*_*ars 15

如果您使用的是PostgreSQL,则以下内容可能有效:

from django.db.models import Count

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

我不确定extract其他数据库的可移植性如何.

  • 使用`connection.ops.date_trunc_sql('month','date')`而不是硬编码提取SQL会使语句与其他后端兼容 (4认同)

小智 13

from django.db import connections
from django.db.models import Count

Link.objects.extra(select={'month': connections[Link.objects.db].ops.date_trunc_sql('month', 'pub_date')}).values('month').annotate(dcount=Count('pub_date'))
Run Code Online (Sandbox Code Playgroud)