Django model group by datetime's date

前端 未结 2 1085
太阳男子
太阳男子 2020-12-14 04:37

Assume I have a such model:

class Entity(models.Model):
    start_time = models.DateTimeField()

I want to regroup them as list of l

2条回答
  •  甜味超标
    2020-12-14 05:11

    Create a small function to extract just the date:

    def extract_date(entity):
        'extracts the starting date from an entity'
        return entity.start_time.date()
    

    Then you can use it with itertools.groupby:

    from itertools import groupby
    
    entities = Entity.objects.order_by('start_time')
    for start_date, group in groupby(entities, key=extract_date):
        do_something_with(start_date, list(group))
    

    Or, if you really want a list of lists:

    entities = Entity.objects.order_by('start_time')
    list_of_lists = [list(g) for t, g in groupby(entities, key=extract_date)]
    

提交回复
热议问题