我有一个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
答案 0 :(得分:0)
使用注释方法计算得分差异,然后按顺序排序 用那个计算的字段。
Post.objects.annotate(score_diff=F('upvotes') - F('downvotes')).order_by('-score_diff')