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?
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')
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With