Joey Fran
Joey Fran

Reputation: 627

Django ORM grouping by hour excluding minutes

Hello I'm trying to grouping a django query by hour excluding minutes.

Let me show a example:

[...]
date_example = models.DateTimeField("My Example", blank=True, null=True)
quantity = models.IntegerField("Quantity", default=1)
[...]

In my head this example should work:

ModelExample.objects.values("date_example__hour").annotate(total_quantity=Sum("quantity"))

But the output takes into account minutes and seconds.

Is there a way to group by hour excluding minutes and seconds?

Example: the group has 7 hours inside (7:00, 7:20, 7:45)

Upvotes: 1

Views: 46

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

You can use ExtractHour [Django-doc] for that:

from django.db.models import Sum
from django.db.models import ExtractHour

ModelExample.objects.values(
    hour=ExtractHour('date_example')
).annotate(
    total_quantity=Sum('quantity')
).order_by('hour')

Upvotes: 2

Related Questions