2017-03-08 54 views
0

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

Calculate the score difference with annotate method and then order by with that calculated field.

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

这工作,但它的排序由刚刚upvotes? Not upvotes - downvotes – Zorgan

+0

你可以用score_diff数据显示你的示例输出吗?或者对这个对象有一个for循环,然后打印score_diff并检查结果是否正确? – Aniket

+1

我的错误是我的downvote视图无法正常工作。 annotate()代码完美,谢谢。 – Zorgan

相关问题