获取按天分组的最后几天创建的对象列表

时间:2018-10-15 14:02:49

标签: python django

我需要获取按天分组的最近几天创建的对象列表,以便在图表中显示数据。

我有这个模型:

class Model(Base):
    ...
    created = DateTimeField(default=timezone.now(), editable=False)
    ...

现在我这样做:

Model.objects.filter(
    created__date__lte=today,
    created__date__gte=today-delta
).values('created').annotate(count=Count('id'))

但是,我得到了以下查询集:

<SoftDeletableQuerySet [{'created': datetime.datetime(2018, 10, 15, 13, 5, 35, 208157, tzinfo=<UTC>), 'count': 1}, {'created': datetime.datetime(2018, 10, 15, 13, 5, 35, 297617, tzinfo=<UTC>), 'count': 1}, {'created': datetime.datetime(2018, 10, 15, 13, 5, 35, 385555, tzinfo=<UTC>), 'count': 1}, {'created': datetime.datetime(2018, 10, 15, 13, 5, 35, 474287, tzinfo=<UTC>), 'count': 1}, {'created': datetime.datetime(2018, 10, 15, 13, 5, 35, 507464, tzinfo=<UTC>), 'count': 1}, {'created': datetime.datetime(2018, 10, 15, 13, 5, 35, 552092, tzinfo=<UTC>), 'count': 1}, {'created': datetime.datetime(2018, 10, 15, 13, 5, 35, 585314, tzinfo=<UTC>), 'count': 1}, {'created': datetime.datetime(2018, 10, 15, 13, 5, 35, 618656, tzinfo=<UTC>), 'count': 1}, {'created': datetime.datetime(2018, 10, 15, 13, 5, 35, 652501, tzinfo=<UTC>), 'count': 1}, {'created': datetime.datetime(2018, 10, 15, 13, 5, 35, 696849, tzinfo=<UTC>), 'count': 1}]>

如您所见,对象是按创建日期分组的,但是此字段是DateTimeField而不是DateField,因此是以毫秒为单位分组的。

我正在尝试这样做:

Model.objects.filter(
    created__date__lte=today,
    created__date__gte=today-delta
).values('created__date').annotate(count=Count('id'))

但是出现以下错误:

FieldError: Cannot resolve keyword 'date' into field. Join on 'created' not permitted.

我认为我需要的是很普通的,并且必须有某种DRY方式才能做到这一点。

1 个答案:

答案 0 :(得分:2)

您可以将.annotate(..)TruncDate [Django-doc]表达式一起使用以截断日期:

from django.db.models.functions import TruncDate

Model.objects.filter(
    created__date__lte=today,
    created__date__gte=today-delta
).annotate(
    day=TruncDate('created')
).values('day').annotate(
    count=Count('id')
).order_by('day')

.order_by是必需的,因为否则您不会“强制” Django使用GROUP BY,因此Count('id')将不包含该特定日期的项目总数

相关问题