python - Django自定义order_by算法

标签 python django algorithm sql-order-by

我想为热门帖子创建一个公式。到目前为止我已经这样做了:

def hot(request):
    posts = Post.objects.all()
    for post in posts:
        likes = int(post.likes)
        views = int(post.blog_view)
        rep = int(post.author.profile.reputation)
        d0 = timezone.now()
        d1 = post.date_posted
        days = (d0 - d1).days
        trending_score = (3/(1+days**(1/3)))*(0.5*views+0.25*rep+2.5*likes)

该公式位于 trending_score 变量中,每次都会返回一个数字作为其趋势分数。 trending_score 越高,它就越热门。

现在我想在 django 中使用 order_by 或其他东西来实现这个:

def hot(request):
    posts = Post.objects.all()
    for post in posts:
        likes = int(post.likes)
        views = int(post.blog_view)
        rep = int(post.author.profile.reputation)
        d0 = timezone.now()
        d1 = post.date_posted
        days = (d0 - d1).days
        trending_score = (3/(1+days**(1/3)))*(0.5*views+0.25*rep+2.5*likes)
    context = {
        Post.objects.all().order_by(-trending_score)
    }
    return render(request, 'blog/popularity.html', context)

我显然知道这行不通,因为我将 trending_score 放在 for 循环中,而上下文位于循环之外,所以它行不通。错误是:无效的 order_by 参数:[-21.75] 但我不知道还能怎么做。对此的任何帮助将不胜感激。

最佳答案

您可以annotate您的查询集包含通过公式计算的值,然后根据注释对其进行排序。主要的事情是将您的公式转换为 django ORM 可以理解的表示形式,以便将其转换为正确的 SQL 语句。像这样的东西应该有效:

from django.db.models import F, FloatField, DurationField
from django.db.models.functions import Cast, Now, Extract


days = Cast(
    Extract(Cast(Now() - F('date_posted'), DurationField()), 'days'),
    FloatField()
)
views = Cast('views', FloatField())
rep = Cast('post.author.profile.reputation', FloatField())
likes = Cast('likes', FloatField())

Post.objects.all().annotate(
    trending_score=(3./(1+days**(1/3)))*(.5*views+.25*rep+2.5*likes)
).order_by('-trending_score')

关于python - Django自定义order_by算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67154011/

相关文章:

Django 表单和标题属性

algorithm - 射线的聚类算法

python - 从无服务器文件夹外部导入自制的 Python 模块

python - Python中的2D卷积类似于Matlab的conv2

django - 如何同时使用 safe 和 truncatechars 方法?

python - 如何将 Django 模型上的属性(虚拟字段)公开为 TastyPie ModelResource 中的字段

python - Pytorch张量形状

Python 3 兼容性问题

javascript - 在javascript中将数组本身合并到另一个具有相同键的数组中

java - 在 Stratego 中检测无可移动棋子的算法