django:基于时间范围的聚合查询 [英] django: time range based aggregate query

查看:550
本文介绍了django:基于时间范围的聚合查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模特,Art和ArtScore:

I have the following models, Art and 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。

Certain user actions results in an ArtScore entry, for instance whenever you click 'I like this art', I save a certain amount of ArtScore for that Art.

现在我试图显示一个本周最受欢迎的页面 ',所以我需要一个仅在该时间范围内聚合ArtScore数量的查询。

Now I'm trying to show a page for 'most popular this week', so I need a query aggregating only ArtScore amounts for that time range.

我构建了下面的查询,但它有缺陷...

I built the below query but it's flawed...

popular = Art.objects.filter(
    artscore__date__range=(weekago, today)
).annotate(
    score=Sum('artscore__amount')
).order_by('-score')

...因为它只排除了不哈哈的艺术在日期范围内有一个ArtScore记录,但不排除日期范围之外的ArtScore记录。

... because it only excludes Art that doesn't have an ArtScore record in the date range, but does not exclude the ArtScore records outside the date range.

任何指针如何完成此操作谢谢,

Any pointers how to accomplish this would be appreciated!

感谢,

Martin

推荐答案

它看起来像这样:
http://docs.djangoproject.com/en/dev/topics/db/aggregation/#order-of-annotate-and-filter-clauses 你应该做什么你想要的是文件错了吗?可能是错误?

it looks like according to this: http://docs.djangoproject.com/en/dev/topics/db/aggregation/#order-of-annotate-and-filter-clauses what you have should do what you want. is the documentation wrong? bug maybe?


第二个查询将只包含
注释计数中的好书。

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

将此更改为您的查询(忘记了现在的订单):

change this to your query (forget about the order for now):

Art.objects.filter(
    artscore__date__range=(weekago, today)
).annotate(
    score=Sum('artscore__amount')
)

现在我们可以说


该查询只会在日期中包含artcores
注释
总额范围。

"the query will only include artscores in the date range in the annotated sum."

这篇关于django:基于时间范围的聚合查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆