Django model group by datetime's date

♀尐吖头ヾ 提交于 2019-12-30 00:17:09

问题


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:


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



回答2:


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.



来源:https://stackoverflow.com/questions/3388559/django-model-group-by-datetimes-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!