基于中的时间聚合字段

2024-04-25 21:04:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个模型:

class MyModel(Model):
    pub_date = DateTimeField(auto_now_add=True)
    hours = IntergerField()

    def get_weekly_hours(self)
        # Find a week-ago interval based on the pub_date
        # Then based on the interval found above, aggregate the...
        # Sum the `hours` altogether
        pass

如何获取时间间隔,然后在此基础上求和?你知道吗


Tags: the模型addautodatemodelonnow
2条回答
from datetime import timedelta
from django.db.models import Sum
from django.utils import timezone

MyModel.objects.filter(
    pub_date__gte=timezone.now() - timedelta(days=7)
).aggregate(sum_hours=Sum('hours'))

请检查下一个链接:

  1. timedelta
  2. range
  3. aggregation

相关问题 更多 >