Search code examples
pythondjangomodels

Aggregate a field based on time interval


I have a model like this:

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

How grab the time interval, then sum based on that?


Solution

  • 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'))