Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

python - Django model group by datetime's date

Assume I have a such model:

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

I want to regroup them as list of lists which each list of lists contains Entities from the same date (same day, time should be ignored).

How can this be achieved in a pythonic way ?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...