实现'趋势'算法来对帖子的查询集进行排序

时间:2017-10-24 02:11:10

标签: python django algorithm

我有一个用于用户帖子的Post模型,还有PostScore模型用于跟踪Post的得分,以便按trending对查询集进行排序,类似reddit的'热门':

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)

我如何分类这些帖子?我会在PostScore下制作自定义方法:

    @property
    def trending(self):
        score = self.upvotes - self.downvotes
        time = self.post.date
        print('TIME:', time)
        return score

或者我会在我的观点中对其进行排序?:

posts = Post.objects.all().filter(entered_category=category).annotate(
    score_diff=F('score__upvotes') - F('score__downvotes'))\
    .order_by('score_diff')

1 个答案:

答案 0 :(得分:0)

我认为在这种情况下使用额外的Managers方法可能是个好主意。 (https://docs.djangoproject.com/en/1.11/topics/db/managers/#adding-extra-manager-methods