Django group by hour

后端 未结 3 535
情深已故
情深已故 2021-01-01 05:42

I have the following model in Django.

class StoreVideoEventSummary(models.Model):
    Customer = models.ForeignKey(GlobalCustomerDirectory, null=True, db_col         


        
相关标签:
3条回答
  • 2021-01-01 06:06

    just break it into two steps

    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)
    

    this allows you to group by several distinct criteria

    if you just want the hour regardless of date just change date_hour

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

    if you wanted to group by day of the week you just use

    def date_hour(timestamp):
       return datetime.datetime.fromtimestamp(timestamp).strftime("%w %H")
    
    0 讨论(0)
  • 2021-01-01 06:16

    I know I'm late here, but taking cues from the doc, https://docs.djangoproject.com/en/1.11/ref/models/querysets/#django.db.models.query.QuerySet.extra

    the below filter should work for you.

    store_count_events = StoreVideoEventSummary.objects.filter(
        Timestamp__range=(start_time, end_time),
        Customer__id=customer_id,
        Store__StoreName=store
    ).order_by(
        'Timestamp'
    ).extra(
        select={
            'hour': 'hour(Timestamp)'
        }
    ).values(
        'hour'
    ).annotate(
        TotalPeople=Sum('PeopleCount')
    )
    
    0 讨论(0)
  • 2021-01-01 06:17

    Building off your original code, could you try:

    store_count_events = StoreVideoEventSummary.objects.filter(Timestamp__range=(start_time, end_time), Customer__id=customer_id, Store__StoreName=store)\
        .extra({
            "hour": "date_part(\'hour\', \"Timestamp\")"
        })\
        .values("hour")\
        .group_by("hour")\
        .annotate(TotalPeople=Sum("PeopleCount"))
    
    0 讨论(0)
提交回复
热议问题