views:

33

answers:

1

Hello 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

+1  A: 

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)]
nosklo
Unless I'm missing something, that will group by date *and* time, when OP wants to group by date only. You might be interested in this article: http://stackoverflow.com/questions/1236865/grouping-dates-in-django
Jordan Reiter
@Jordan Reiter: the question was edited. I've edited the answer and now it works as OP wants.
nosklo
works well, thanks alot!
Hellnar