Django 按小时/天分组

Rah*_*rma 4 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)
Run Code Online (Sandbox Code Playgroud)

我正在尝试绘制预定日期和体重之间的图表。我想按小时和相应的重量对时间戳进行分组。我怎样才能做到这一点?

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

应该是这样的:

data = DispatchPlan.objects.all().groupby('scheduled_date')
Run Code Online (Sandbox Code Playgroud)

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

编辑:我尝试过的

dataset = DispatchPlan.objects.annotate(month=TruncMonth('scheduled_date')).values('month').annotate(c=sum('weight')).values('month', 'c')
Run Code Online (Sandbox Code Playgroud)

错误:

类型错误:+ 不支持的操作数类型:“int”和“str”

Zat*_*ras 6

您需要使用 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')
Run Code Online (Sandbox Code Playgroud)

因为您似乎想按小时分组,所以您应该使用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',
)

Run Code Online (Sandbox Code Playgroud)