python - Django Query 设置用于计算每个月的记录

标签 python django django-queryset

class Orders(models.Model):
  orderid = models.IntegerField(db_column='orderID', primary_key=True) 
  pickupdate = models.DateField(db_column='pickupDate', blank=True, null=True)  

我想在模型中显示每个月的总记录。我找到的解决方案要求我输入年份
Orders.objects.filter(pickupdate__year = '2006').values_list('pickupdate__month').annotate(total = Count('orderid')

上面查询集的结果是这样的:
<QuerySet [(1, 31), (2, 27), (3, 31), (4, 30), (5, 31), (6, 29), (7, 30), (8, 31), (9, 30), (10, 31), (11, 30),
 (12, 31)]>

我希望查询集能够自动从数据库中获取每月范围,而无需将年份放入查询集

我想显示的数据是这样的:
Month        | Total 
January 2007 | 1
February 2007| 2
etc


enter code here

最佳答案

使用 TruncMonth db 函数从日期字段中提取月份

做这样的事情,

from django.db.models import Count
from django.db.models.functions import TruncMonth

Orders.objects.annotate(month=TruncMonth('pickupdate')).values('month').annotate(total=Count('orderid'))

这个 ORM 将生成一个 SQL 查询,
SELECT django_date_trunc('month', "sample_orders"."pickupDate") AS "month", COUNT("sample_orders"."orderID") AS "total" FROM "sample_orders" GROUP BY django_date_trunc('month', "sample_orders"."pickupDate")

示例
In [8]: from django.db.models import Count

In [9]: from django.db.models.functions import TruncMonth

In [10]: Orders.objects.annotate(month=TruncMonth('pickupdate')).values('month').annotate(total=Count('orderid'))
Out[10]: <QuerySet [{'month': datetime.date(2018, 8, 1), 'total': 2}, {'month': datetime.date(2018, 9, 1), 'total': 4}]>

关于python - Django Query 设置用于计算每个月的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52354104/

相关文章:

python - 我可以在 selenium 运行时最小化 chrome 窗口吗?

mysql - Django queryset 选择在哪里连接

django - 从具有多对多关系django的两个表中过滤数据

python - 为什么我的 SGD 与我的线性回归模型相去甚远?

python - 有没有比 np.where 更好的方法使用条件语句来索引大型数组?

python - 如何使用特定用户拥有的对象创建 ModelForm

python - 使用 redis-py(redis 上的 python 包装器)与远程 redis 服务器通信

django - EC2 hosts Django with IP address can't be assigned-to 错误

mysql - Django 1.8 中的复杂注释

python - 使用python从多个文件导入数据