如何在模型中创建一个函数就像一个字段?

时间:2017-03-08 05:12:29

标签: python django django-models

我有一个Post模型,通过ForeignKey链接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

1 个答案:

答案 0 :(得分:0)

  

使用注释方法计算得分差异,然后按顺序排序   用那个计算的字段。

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