我有一个模特:
Model.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和权重之间绘制图表。我想按小时和重量将时间戳分组。 我该怎么办?
在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:+不支持的操作数类型:“ int”和“ str”
答案 0 :(得分:1)
您需要使用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',
)