Djangovoiting排序ord的Hacker-News算法

2024-10-04 11:30:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用django-voting开发一个应用程序,并使用Eric Florenzano's custom VoteAwareManager technique对主页项进行排序:

模型.py

class VoteAwareManager(models.Manager):
    """ Get top votes. hot = VoteAwareManager() """
    def _get_score_annotation(self):
        model_type = ContentType.objects.get_for_model(self.model)
        table_name = self.model._meta.db_table
        return self.extra(select={
            'score': 'SELECT COALESCE(SUM(vote),0) FROM %s WHERE content_type_id=%d AND object_id=%s.id' %
                (Vote._meta.db_table, int(model_type.id), table_name)
                }
        )

    def most_loved(self,):
        return self._get_score_annotation().order_by('-score')

    def most_hated(self):
        return self._get_score_annotation().order_by('score')

class Post(models.Model):
    """Post model"""
    title = models.CharField(_("title"), max_length=200, blank=False)
    slug = models.SlugField(_("slug"), blank=True)
    author = models.ForeignKey(User, related_name="added_posts")
    kind = models.CharField(max_length=1, choices=KIND, default=1)
    url = models.URLField(blank=True, null=True, help_text="The link URL", default='')
    content_markdown = models.TextField(_("Entry"), blank=True)
    content_html = models.TextField(blank=True, null=True, editable=False)
    status = models.IntegerField(_("status"), choices=STATUS_CHOICES, default=IS_PUBLIC)
    allow_comments = models.BooleanField(_("Allow Comments?"), blank=False, default=1)
    created_at = models.DateTimeField(_("created at"), default=datetime.now)
    updated_at = models.DateTimeField(_("updated at"))

    objects = models.Manager()
    hot = VoteAwareManager()

视图.py

^{pr2}$

我现在想把Hacker New's ranking algorithm与上面的代码结合起来,这样旧的项目排名就会下降,但是我遇到了麻烦。我不确定相关的代码是应该进入VoteAwareManager函数,还是最受欢迎的方法,还是其他地方。

以下是我尝试过的:

1。在最受欢迎的方法中进行计算:返回TypeError at / unsupported operand type(s) for -: 'QuerySet' and 'int'(当使用随机时间戳来查看是否可以得到结果时,最终我还需要弄清楚如何获得对象时间戳-我是一个初级程序员):

def most_loved(self):
    totalscore = self._get_score_annotation()
    time_stamp = 20120920
    gravity = 1.8
    return (totalscore - 1) / pow((time_stamp+2), gravity)

2。SQL中的计算:返回TemplateSyntaxError at / Caught DatabaseError while rendering: column "votes.time_stamp" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: ...(SELECT COALESCE(SUM(vote),0 / (EXTRACT(HOUR FROM TIME_STAMP...

class VoteAwareManager(models.Manager):
""" Get top votes. hot = VoteAwareManager() """
def _get_score_annotation(self):
    model_type = ContentType.objects.get_for_model(self.model)
    table_name = self.model._meta.db_table
    return self.extra(select={
        'score': 'SELECT COALESCE(SUM(vote),0 / (EXTRACT(HOUR FROM TIME_STAMP)+2 * 1.8)) FROM %s WHERE content_type_id=%d AND object_id=%s.id' % 
        (Vote._meta.db_table, int(model_type.id), table_name)
        }
    )

一种选择是尝试将投票系统改为使用django-rangevoting,但是如果可能的话,我希望使用django投票。非常感谢你的帮助。在


Tags: nameselfidtruegetmodelmodelsdef
1条回答
网友
1楼 · 发布于 2024-10-04 11:30:57

不是完美的(省略-1减法来否定用户自己的投票),但目前看来这已经足够好了:

class VoteAwareManager(models.Manager):
""" Get recent top voted items (hacker news ranking algorythm, without the -1 for now since it breaks the calculation as all scores return 0.0)
    (p - 1) / (t + 2)^1.5
    where p = points and t = age in hours
"""
def _get_score_annotation(self):
    model_type = ContentType.objects.get_for_model(self.model)
    table_name = self.model._meta.db_table

    return self.extra(select={

        'score': 'SELECT COALESCE(SUM(vote / ((EXTRACT(EPOCH FROM current_timestamp - created_at)/3600)+2)^1.5),0) FROM %s WHERE content_type_id=%d AND object_id=%s.id' % (Vote._meta.db_table, int(model_type.id), table_name)

        })

def most_loved(self):        
    return self._get_score_annotation().order_by('-score',)

相关问题 更多 >