Rahul Sharma
Rahul Sharma

Reputation: 2495

Django group by hour/day

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'

Upvotes: 4

Views: 2782

Answers (1)

Zathras
Zathras

Reputation: 434

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

Upvotes: 6

Related Questions