Django ORM 按小时分组,不包括分钟

Django ORM grouping by hour excluding minutes

您好,我正在尝试按小时(不包括分钟)对 Django 查询进行分组。

举个例子:

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

在我看来,这个例子应该可行:

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

但是输出会考虑分秒。

有没有办法按小时分组,不包括分秒?

示例:小组内有 7 个小时(7:00,7:20,7:45)

您可以使用 ExtractHour [Django-doc]

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

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