python - 根据过去 7 天在 django 中创建权重逻辑

标签 python django

我目前有一个 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)

最佳答案

我希望这会有所帮助:

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不过滤掉restaurants没有 reviewscomments 。如果你不关心那些restaurants ,您可以使用此过滤器:

filter(review__pub_date__gt=week_ago, comment__pub_date__gt=week_ago)

文档

关于python - 根据过去 7 天在 django 中创建权重逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38490612/

相关文章:

python - PyCharm/ python 。代码不运行。立即收到 "Getting Process finished with exit code 0"

python - 如何在 Django Elasticsearch 中映射关键字字段?

python - Django 日期输入解析?

python - 根据另一个类在 django 中动态加载特定应用程序的最佳方法是什么?

css - 找不到或无法读取要导入的文件 : bootstrap-sass

python - 意外的诅咒前/背景 256 色 init_pair'ing

python - 设置python rpm的安装路径

python - 在 ubuntu 中卸载 python 模块

python - 如何访问 django 模板中的 django ManyToManyField

python - Django,ModelMultipleChoiceField 中的初始值仅设置为禁用