gpt4 book ai didi

python - Django 按年/月计数分组,无需额外

转载 作者:太空狗 更新时间:2023-10-29 23:58:08 24 4
gpt4 key购买 nike

我正在使用 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() 而不是 Q(date__year)表示 EXTRACT(year FROM date) 函数的表达式,并在 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'))

关于python - Django 按年/月计数分组,无需额外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35368274/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com