11

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

Hellnar
  • 62,315
  • 79
  • 204
  • 279
  • Possible duplicate of [Django: Group by date (day, month, year)](http://stackoverflow.com/questions/8746014/django-group-by-date-day-month-year) – tback Jun 24 '16 at 07:26

2 Answers2

17

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
  • 217,122
  • 57
  • 293
  • 297
  • 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 Aug 02 '10 at 17:07
  • @Jordan Reiter: the question was edited. I've edited the answer and now it works as OP wants. – nosklo Aug 02 '10 at 18:23
10

I agree with the answer:

Product.objects.extra(select={'day': 'date( date_created )'}).values('day') \
               .annotate(available=Count('date_created'))

But there is another point that: the arguments of date() cannot use the double underline combine foreign_key field, you have to use the table_name.field_name

result = Product.objects.extra(select={'day': 'date( product.date_created )'}).values('day') \
           .annotate(available=Count('date_created'))

and product is the table_name

Also, you can use "print result.query" to see the SQL in CMD.

Lee
  • 181
  • 2
  • 5