在Djang中注释导致“None”值的SUM聚合函数

2024-04-19 22:13:23 发布

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

做我的第一个真正的Django项目,需要指导。

背景: 我的项目是reddit的克隆。用户提交链接+文本。访客投赞成票或反对票。有一个社交排名算法,每~2分钟运行一次作为背景脚本,根据网络投票和内容新鲜度重新排列所有提交的内容。相当香草的东西。

问题:votes排序无法正常工作,因为votes正在初始化为None,而不是0。这会导致投None票的提交低于投反对票的提交。我已经调试这个问题好几天了-不走运。

细节: 我已经重写了模型的模型管理器,将一个Sum聚合函数注释到查询集,然后按“社会等级”和投票排序所述查询集。

下面是我的模型.py。我正在使用Django 1.5,因此您在这里看到的某些内容可能与1.8不对应(例如get_query_setget_queryset):

class LinkVoteCountManager(models.Manager):
    def get_query_set(self):
        return super(LinkVoteCountManager, self).get_query_set().annotate(votes=Sum('vote__value')).order_by('-rank_score', '-votes') 

class Link(models.Model):
    description = models.TextField(_("Write something"))
    submitter = models.ForeignKey(User)
    submitted_on = models.DateTimeField(auto_now_add=True)
    rank_score = models.FloatField(default=0.0)
    url = models.URLField(_("Link"), max_length=250, blank=True)

    with_votes = LinkVoteCountManager() 
    objects = models.Manager() 

    def __unicode__(self): 
        return self.description

    def set_rank(self):
        # Based on reddit ranking algo at http://amix.dk/blog/post/19588
        epoch = datetime(1970, 1, 1).replace(tzinfo=None)
        netvotes = self.votes # 'NONE' votes are messing up netvotes amount.
        if netvotes == None:
            netvotes = 0
        order = log(max(abs(netvotes), 1), 10)
        sign = 1 if netvotes > 0 else -1 if netvotes < 0 else 0
        unaware_submission = self.submitted_on.replace(tzinfo=None)
        td = unaware_submission - epoch 
        epoch_submission = td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)
        secs = epoch_submission - 1432201843
        self.rank_score = round(sign * order + secs / 45000, 8)
        self.save()

class Vote(models.Model):
    voter = models.ForeignKey(User)
    link = models.ForeignKey(Link)
    value = models.IntegerField(null=True, blank=True, default=0)

    def __unicode__(self):
        return "%s gave %s to %s" % (self.voter.username, self.value, self.link.description)

如果需要,以下是myviews.py中的相关部分:

class LinkListView(ListView):
    model = Link
    queryset = Link.with_votes.all()
    paginate_by = 10

    def get_context_data(self, **kwargs):
        context = super(LinkListView, self).get_context_data(**kwargs)
        if self.request.user.is_authenticated():
            voted = Vote.objects.filter(voter=self.request.user)
            links_in_page = [link.id for link in context["object_list"]]
            voted = voted.filter(link_id__in=links_in_page)
            voted = voted.values_list('link_id', flat=True)
            context["voted"] = voted
        return context

class LinkCreateView(CreateView):
    model = Link
    form_class = LinkForm

    def form_valid(self, form):
        f = form.save(commit=False)
        f.rank_score=0
        f.with_votes = 0
        f.category = '1'
        f.save()
        return super(CreateView, self).form_valid(form)

有人能告诉我需要做什么来解决“None”问题吗?提前谢谢。


Tags: selfformnonegetreturnmodelsdefcontext
2条回答

你也可以换线

netvotes = self.votes

netvotes = self.votes or 0

现在可以删除if语句。

与许多其他语言一样,它的作用是返回非falsy值(None,0,“”),或者在这种特殊情况下返回最后一个值“0”。

尽管我选择了通过从结果中排除条目来忽略None条目,但还是遇到了同样的问题。我猜你不想那样。

顺便说一下,这个问题也有同样的问题Annotating a Sum results in None rather than zero

至于解决方案,除了使用该问题的答案中指出的自定义sql之外,您可以使用Django 1.8,并使用Django的bug tracker中打开的票证中指出的超过6年的解决方案(!)https://code.djangoproject.com/ticket/10929

Coalesce(Sum('field'), 0)

所以你的经理会:

class LinkVoteCountManager(models.Manager):
    def get_query_set(self):
        return super(LinkVoteCountManager, self).get_query_set().annotate(
            votes=Coalesce(Sum('vote__value'), 0)
        ).order_by(
            '-rank_score', 
            '-votes'
        )

注:我没有测试代码,因为我自己也没有使用Django 1.8。

相关问题 更多 >