我目前有一个 Restaurant
模型以及关联的模型 Review
和 Comment
。用户可以对餐厅进行评论和评论。
我正在尝试在 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)
最佳答案
我希望这会有所帮助:
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=True
和comment__isnull=True
不过滤掉restaurants
没有 reviews
和comments
。如果你不关心那些restaurants
,您可以使用此过滤器:
filter(review__pub_date__gt=week_ago, comment__pub_date__gt=week_ago)
文档
关于python - 根据过去 7 天在 django 中创建权重逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38490612/