我有以下模型,Art 和 ArtScore:
class Art(models.Model):
title = models.CharField()
class ArtScore(models.Model):
art = models.ForeignKey(Art)
date = models.DateField(auto_now_add = True)
amount = models.IntegerField()
某些用户操作会产生 ArtScore 条目,例如,每当您单击“我喜欢这件艺术品”时,我就会为该艺术品保存一定数量的 ArtScore。
现在我正在尝试显示“本周最受欢迎”的页面,因此我需要一个仅聚合该时间范围内的 ArtScore 金额的查询。
我构建了以下查询,但它有缺陷......
popular = Art.objects.filter(
artscore__date__range=(weekago, today)
).annotate(
score=Sum('artscore__amount')
).order_by('-score')
...因为它仅排除该日期范围内没有 ArtScore 记录的艺术,但不排除该日期范围之外的 ArtScore 记录。
任何关于如何实现这一点的指示将不胜感激!
谢谢
马丁
最佳答案
看起来像这样: http://docs.djangoproject.com/en/dev/topics/db/aggregation/#order-of-annotate-and-filter-clauses你所拥有的应该做你想做的。文档有错吗?也许是错误?
"the second query will only include good books in the annotated count."
关于:
>>> Publisher.objects.filter(book__rating__gt=3.0).annotate(num_books=Count('book'))
将其更改为您的查询(暂时忘记订单):
Art.objects.filter(
artscore__date__range=(weekago, today)
).annotate(
score=Sum('artscore__amount')
)
现在我们可以说
"the query will only include artscores in the date range in the annotated sum."
关于django:基于时间范围的聚合查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1729222/