根据时间间隔聚合字段

Aggregate a field based on time interval

我有这样一个模型:

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

如何抓取时间间隔,然后据此求和?

请检查下一个链接:

  1. timedelta
  2. range
  3. aggregation
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'))