Django group by hour/day

那年仲夏 提交于 2020-12-11 06:01:15

问题


I have a model:

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)

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?

In SQl its just like .groupby('scheduled_date) but since it's a timestamp, I don't think it's the same

Should it be like:

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

I am using postgres as my database.

Edit: what I tried

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

error:

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


回答1:


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')

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',
)



来源:https://stackoverflow.com/questions/56438461/django-group-by-hour-day

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!