Django计算按年/月分组,没有额外的

时间:2016-02-12 17:03:36

标签: python django aggregate annotate

我正在使用django 1.9

型号:

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

由于'extra()'将在django中弃用,我试图弄清楚如何按年份计算评论组而不使用'额外'

这是带有额外代码的代码:

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

感谢您的帮助。

1 个答案:

答案 0 :(得分:6)

请参阅文档中的year and month,以下内容可能会起作用:

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

如果这不起作用,那么您可以定义代表EXTRACT(year FROM date)函数的自定义Func()表达式而不是Q(date__year),并在annotate()中使用它。或者,作为最后的手段RawSQL()

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