Django - aggregate queryset by week of year
Question: I have model looking like this:

    
    
    class TestData(models.Model):
        name = models.CharField(max_length=255)
        one_value = models.IntegerField()
        second_value = models.IntegerField()
        create_at = models.DateTimeField()
    

Is any way to easy generate queryset of summed values for every week of year?
Django 1.9, Python 3


Answer: 
    from django.db.models import Func, F, Sum
    
    class Week(Func):
        def as_mysql(self, compiler, connection):
            self.function = 'WEEK'
            return super().as_sql(compiler, connection)
    
    data = (TestData.objects
            .filter(create_at__year=year)
            .annotate(week=Week('create_at'))
            .values('week')
            .annotate(Sum('one_value')))
    

Or `Sum(F('one_value') + F('second_value'))`, depending on what sum you want
to get.

