Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django .aggregate() on .annotate()

Is it possible to aggregate the annotations of a queryset?

Models:

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

error:

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

When running this, I get a DatabaseError as django tries to do the aggregation on the 'views' and 'download' database columns instead of doing it on the annotations.

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

like image 946
MauroMSL Avatar asked Jun 22 '15 16:06

MauroMSL


1 Answers

I think medmunds is right, you cannot re-use the same name for annotate and aggregate alias. This is what you want to do, I think:

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')
)
like image 196
Bruno A. Avatar answered Oct 18 '22 07:10

Bruno A.