如何在模型中制作功能像字段一样



我有一个Post模型,该模型通过外国键链接wth PostScore

class Post(models.Model):
user = models.ForeignKey(User, blank=True, null=True)
title = models.TextField(max_length=76)
...

class PostScore(models.Model):
    user = models.ForeignKey(User, blank=True, null=True)
    post = models.ForeignKey(Post, related_name='score')
    upvotes = models.IntegerField(default=0)
    downvotes = models.IntegerField(default=0)
    def trending(self):
        score = self.upvotes - self.downvotes
        return score

所以当我尝试对这样的帖子进行分类时:

posts = Post.objects.all().order_by('-score__upvotes')

它可以正常工作,但是我将如何按trending进行排序?:

posts = Post.objects.all().order_by('-score__trending')

以上代码创建此错误:

FieldError at /news/
Cannot resolve keyword 'trending' into field. Choices are: downvotes, id, post, post_id, upvotes, user, user_id

用注释方法计算得分差,然后按 使用该计算的字段。

Post.objects.annotate(score_diff=F('upvotes') - F('downvotes')).order_by('-score_diff')

最新更新