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

该博客讨论了在Django中如何正确构造查询来获取指定一周内最受欢迎的艺术作品。作者遇到的问题是,当前的查询只排除了没有评分记录的艺术作品,但并未排除评分记录在日期范围之外的情况。解决方案是根据Django的文档,确认查询应该能够仅包含在日期范围内的评分记录进行聚合。这涉及到过滤和聚合操作的正确顺序,以确保聚合的分数仅基于指定时间范围内的评分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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.

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

... 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!

Thanks,

Martin

解决方案

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."

in regards to:

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

)

now we can say

"the query will only include artscores

in the date range in the annotated

sum."

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值