Django 计数按 year/month 分组,无需额外

Django count grouping by year/month without extra

我正在使用 django 1.9

型号:

class Comment(models.Model):
    title = models.CharField(max_length=250, null=False)
    date = models.DateField(auto_now_add=True)

由于 'extra()' 将在 django 中被弃用,我试图弄清楚如何在不使用 'extra'

的情况下按年月计算评论组

这是额外的代码:

Comment.objects.extra(select={'year': "EXTRACT(year FROM date)",
    'month': "EXTRACT(month from date)"})\
    .values('year', 'month').annotate(Count('pk'))

感谢您的帮助。

请参阅文档中的 year and month,可能像下面这样的东西就可以完成工作:

Comment.objects.annotate(year=Q(date__year), 
                         month=Q(date__month)
                         ).values('year', 'month').annotate(Count('pk'))

如果这行不通,那么您可以定义自定义 Func() expression representing EXTRACT(year FROM date) function and use it in annotate(). Or, well, as last resort there's RawSQL().

而不是 Q(date__year)

使用 Func(),像这样:

from django.db.models import Func

class Extract(Func):
    """
    Performs extraction of `what_to_extract` from `*expressions`.

    Arguments:
        *expressions (string): Only single value is supported, should be field name to
                               extract from.
        what_to_extract (string): Extraction specificator.

    Returns:
        class: Func() expression class, representing 'EXTRACT(`what_to_extract` FROM `*expressions`)'.
    """

    function = 'EXTRACT'
    template = '%(function)s(%(what_to_extract)s FROM %(expressions)s)'


#Usage
Comment.objects.annotate(year=Extract(date, what_to_extract='year'), 
                             month=Extract(date, what_to_extract='month')
                             ).values('year', 'month').annotate(Count('pk'))