Skip to main content
 首页 » 编程设计

python之Django 按小时/天分组

2024年09月03日34kenshinobiy

我有一个模型:

模型.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', 
)