注释SUM聚合函数,在Django中导致'None'值

Has*_*aig 9 python django django-models django-queryset django-aggregation

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

背景: 我的项目是一个reddit克隆.用户提交链接+文本.访客upvote或downvote.有一个社交驱动算法,每隔约2分钟作为背景脚本运行,根据净投票和内容的新鲜度重新提交所有提交.相当香草的东西.

问题: 排序votes不正常,因为votes正在初始化None而不是0.这导致None投票的提交排名低于负投票的提交.我已经调试了这个问题好几天 - 没有运气.

细节: 我已经过度使用我的模型的模型管理器来Sum为查询集注释聚合函数,然后通过"社会等级"和投票来对所述查询集进行排序.

下面是我的models.py.我正在使用Django 1.5,因此你在这里看到的一些东西可能与1.8不相符(例如get_query_setvs get_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)
Run Code Online (Sandbox Code Playgroud)

如果需要,以下是我的views.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)
Run Code Online (Sandbox Code Playgroud)

任何人都可以阐明我需要做些什么来解决" None"问题?提前致谢.

alf*_*ito 21

只是碰到了同一堵墙,虽然我选择忽略None条目,将它们排除在结果之外.猜猜你不想那样.

顺便说一句,这个问题有相同的问题注释一个Sum会导致None而不是零

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

Coalesce(Sum('field'), 0)
Run Code Online (Sandbox Code Playgroud)

所以你的经理会:

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'
        )
Run Code Online (Sandbox Code Playgroud)

PS:我没有测试过代码,因为我自己并没有使用Django 1.8.


小智 5

你也可以更换线

netvotes = self.votes

netvotes = self.votes or 0

您现在可以删除 if 语句。

这在许多其他语言中所做的是返回非值(None, 0, ""),或者在这种特殊情况下返回最后一个值“0”。