Django 按小时/天分组 [英] Django group by hour/day
问题描述
我有一个模型:
模型.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)
我正在尝试在 schedule_date 和 weight 之间绘制图表.我想相应地按小时和重量对时间戳进行分组.我该怎么做?
and I am trying to plot a graph between scheduled_date and weight. I want to group the timestamp by hour and weight accordingly. How can I do that?
在 SQl 中它就像 .groupby('scheduled_date)
但由于它是一个时间戳,我认为它不一样
In SQl its just like .groupby('scheduled_date)
but since it's a timestamp, I don't think it's the same
应该是这样的:
data = DispatchPlan.objects.all().groupby('scheduled_date')
我使用 postgres 作为我的数据库.
I am using postgres as my database.
我试过的
dataset = DispatchPlan.objects.annotate(month=TruncMonth('scheduled_date')).values('month').annotate(c=sum('weight')).values('month', 'c')
错误:
TypeError: 不支持 + 的操作数类型:'int' 和 'str'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
推荐答案
您需要使用 Django 的 Sum
方法,而不是 Python 的 sum
.所以做这样的事情:
You need to use Django's Sum
method instead of Python's sum
. So do something like this:
from django.db.models import Sum
dataset = DispatchPlan.objects.annotate(month=TruncMonth('scheduled_date')).values('month').annotate(c=Sum('weight')).values('month', 'c')
因为您似乎想按小时分组,所以您应该使用 TrncHour
代替:
As it seems you want to group by hour you should be using TruncHour
instead:
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',
)
这篇关于Django 按小时/天分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!