在Django创建基于过去7天的权重逻辑

2024-04-19 19:08:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前有一个Restaurant模型,其中有关联的模型ReviewComment。用户可以评论和评论餐厅。你知道吗

我试图在Django中创建权重逻辑,其中我显示了权重最大的前三家餐厅。你知道吗

当前的逻辑如下所示:

restaurants = Restaurant.objects.all()
top_3 = restaurants.annotate(weight=(Count('review')) + F('views') + (Count('comment'))).order_by('-weight')

我该如何更新这个逻辑,以便只有过去7天的评论和评论被纳入权重?你知道吗

编辑 Review和Comment模型都有一个用于跟踪对象创建时间的字段: pub_date = models.DateTimeField(default=timezone.now, blank=True)


Tags: django用户模型objectscountcomment评论逻辑
1条回答
网友
1楼 · 发布于 2024-04-19 19:08:26

我希望这将有助于:

import datetime

from django.db.models import Q
from django.utils import timezone    

week_ago = timezone.now() - datetime.timedelta(days=7)
top_3 = Restaurant.objects.filter(
    Q(review__isnull=True) | Q(review__pub_date__gt=week_ago),
    Q(comment__isnull=True) | Q(comment__pub_date__gt=week_ago),
).annotate(weight=...).order_by('-weight')[:3]

review__isnull=Truecomment__isnull=True不过滤掉没有reviewscommentsrestaurants。如果你不关心这些restaurants,你可以使用这个过滤器:

filter(review__pub_date__gt=week_ago, comment__pub_date__gt=week_ago)

文件

相关问题 更多 >