.annotate()上的Django .aggregate()

时间:2015-06-22 16:05:08

标签: python django django-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()

我试图执行以下操作:

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

错误:

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

当运行它时,我得到一个DatabaseError,因为django试图在'视图'上进行聚合。并且'下载'数据库列而不是在注释上执行。

有没有其他方法可以对QuerySet注释进行此聚合?

1 个答案:

答案 0 :(得分:1)

我认为medmunds是对的,你不能为注释和聚合别名重复使用相同的名称。我想你想做的就是:

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