django:基于时间范围的聚合查询

标签 django django-models aggregate django-queryset django-aggregation

我有以下模型,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/

相关文章:

python - Django Model.objects.all() 返回意外的空 QuerySet

django - 在模板中测试 Django 模型选择

mysql - SQL 一对多 JOIN/聚合

MySQL 复合聚合和不正确的语法?

python - 检查ManyToMany字段中的对象是否为Django Rest框架

ajax put 返回 500 内部服务器错误

python - 在 Django 中,如何将具有复合主键的表连接到另一个表?

python - django中具有多个参数的过滤器和链式过滤器之间的区别

python - 计算 Django ORM 中按查询分组的注释字段的最大总和?

python - 将 django sorl-thumbnail 与 django form-utils 一起使用