python - Django 按小时/天分组

标签 python django orm

我有一个模型:

模型.py

class DispatchPlan(models.Model):
    total_trucks = models.IntegerField(default=0)
    material_type = models.CharField(max_length=255, default=0, choices=mtypes)
    scheduled_date = models.DateTimeField(max_length=255, default=0)
    offered_price = models.IntegerField(default=0)
    weight = models.IntegerField(default=0)

我正在尝试绘制 scheduled_date 和 weight 之间的图表。我想相应地按小时和重量对时间戳进行分组。 我该怎么做?

在 SQl 中它就像 .groupby('scheduled_date) 但因为它是一个时间戳,我认为它不一样

应该是这样的:

data = DispatchPlan.objects.all().groupby('scheduled_date')

我正在使用 postgres 作为我的数据库。

编辑: 我尝试了什么

dataset = DispatchPlan.objects.annotate(month=TruncMonth('scheduled_date')).values('month').annotate(c=sum('weight')).values('month', 'c')

错误:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

最佳答案

您需要使用 Django 的 Sum 方法,而不是 Python 的 sum。所以做这样的事情:

from django.db.models import Sum

dataset = DispatchPlan.objects.annotate(month=TruncMonth('scheduled_date')).values('month').annotate(c=Sum('weight')).values('month', 'c')

您似乎想按小时分组,您应该改用 TruncHour:

from django.db.models import Sum
from django.db.models.functions import TruncHour

dataset = DispatchPlan.objects.annotate( 
    hour=TruncHour('scheduled_date')
).values(
    'hour'
).annotate(
    c=Sum('weight')
).values(
    'hour', 
    'c',
)

关于python - Django 按小时/天分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56438461/

相关文章:

python - 电子邮件验证(1062, "Duplicate entry ''对于 key 'email'“)

java - 带 Hibernate 的独立数据库

android - Kivy:声音开始播放,但在Android上为 'unstoppable',但在Windows上有效

python - 使用 python 将内容粘贴到单独的列中

python - 如何在字典列表中查找值并返回特定键

python - 在django中将两个字段相乘

python - Python 中嵌套类的正确语法?

python - 如何理解 Django View 函数的配置文件输出

c# - 有任何 ORM 可以为高速批量插入提供不错的方法吗?

Django:获取相关对象的相关对象并传递给模板