Django.aggregate () to .annotate ()

Can you aggregate queryset annotations?

Model:

class Article(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField()

class State(models.Model):
    article = Models.ForeignKey(Article)
    date = DateField()
    views = IntegerField()
    downloads = IntegerField()

      

I am trying to do the following:

articles = metrics_models.Article.objects.filter(
    state__date__month=month,
    state__date__year=year
).annotate(
    views=Min('state__views'),
    downloads=Min('state__downloads')
).aggregate(
    views=Sum('views'),
    downloads=Sum('downloads')
)

      

Mistake:

Exception Type: DatabaseError
Exception Value:    
column "downloads" does not exist
LINE 1: SELECT SUM(downloads), SUM(views) FROM (SELECT "metrics_arti...

      

When doing this I get a DatabaseError because django is trying to aggregate on the database columns 'views' and 'download' instead of doing it in annotations.

Is there any other way to do this aggregation in QuerySet annotations?

+3


source to share


1 answer


I think medmunds is correct, you cannot reuse the same name for annotation and aggregate alias. I think this is what you want to do:



articles = metrics_models.Article.objects.filter(
    state__date__month=month,
    state__date__year=year
).annotate(
    min_views=Min('state__views'),
    min_downloads=Min('state__downloads')
).aggregate(
    sum_min_views=Sum('min_views'),
    sum_min_downloads=Sum('min_downloads')
)

      

+2


source







All Articles