Django按小时组

Cad*_*nge 2 python django orm group-by

我在Django中有以下模型.

class StoreVideoEventSummary(models.Model):
    Customer = models.ForeignKey(GlobalCustomerDirectory, null=True, db_column='CustomerID', blank=True, db_index=True)
    Store = models.ForeignKey(Store, null=True, db_column='StoreID', blank=True, related_name="VideoEventSummary")
    Timestamp = models.DateTimeField(null=True, blank=True, db_index=True)
    PeopleCount = models.IntegerField(null=True, blank=True)
Run Code Online (Sandbox Code Playgroud)

我想知道每小时进入商店的人数.

为了实现这一点,我试图按小时对行进行分组并对列进行Timestamp求和PeopleCount.

store_count_events = StoreVideoEventSummary.objects.filter(Timestamp__range=(start_time, end_time),
                                                       Customer__id=customer_id,
                                                       Store__StoreName=store)\
        .order_by("Timestamp")\
        .extra({
            "hour": "date_part(\'hour\', \"Timestamp\")"
        }).annotate(TotalPeople=Sum("PeopleCount"))
Run Code Online (Sandbox Code Playgroud)

这似乎不按小时对结果进行分组,它只是添加一个新列TotalPeople,该PeopleCount列与查询集中的每一行具有相同的值.

Jor*_*ley 7

把它分成两步

objs = StoreVideoEventSummary.objects.filter(Timestamp__range=(start_time, end_time),
                                                   Customer__id=customer_id,
                                                   Store__StoreName=store)\
    .order_by("Timestamp")

def date_hour(timestamp):
   return datetime.datetime.fromtimestamp(timestamp).strftime("%x %H")

groups = itertools.groupby(objs, lambda x:date_hour(x.Timestamp))
#since groups is an iterator and not a list you have not yet traversed the list
for group,matches in groups: #now you are traversing the list ...
    print group,"TTL:",sum(1 for _ in matches)
Run Code Online (Sandbox Code Playgroud)

这允许您按几个不同的标准进行分组

如果你只是想要小时而不管日期只是改变 date_hour

def date_hour(timestamp):
   return datetime.datetime.fromtimestamp(timestamp).strftime("%H")
Run Code Online (Sandbox Code Playgroud)

如果你想按照你刚才使用的那一天进行分组

def date_hour(timestamp):
   return datetime.datetime.fromtimestamp(timestamp).strftime("%w %H")
Run Code Online (Sandbox Code Playgroud)