7

做我的第一个真正的Django项目,并且需要指导。在Django中注释导致'None'值的SUM聚合函数

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

问题: 排序方式votes无法正常工作,因为votes被初始化为None,而不是0。这会导致None投票的投稿数量低于提交的反对投票数。我已经调整了这个问题几天 - 没有运气。

具体细节: 我过我缠身模型的模型管理器来标注Sum聚合函数查询集,然后责令该查询通过“社会地位”和投票设置。下面是我的models.py。我使用Django 1.5,这样一些东西,你看到这里可能不符合1.8(如get_query_set VS 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) 

如果需要的话,以下是从我的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) 

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

+0

如果你设置null = False保持默认= 0? –

回答

11

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

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

至于比使用在这个问题的回答指出了一个自定义的SQL其他的解决方案,你可以使用Django 1.8,而不是去为解决中指出, (!)在Django的bug跟踪票开了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' 
     ) 

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

+0

谢谢你这个人! –

+0

@HassanBaig很高兴能帮到你 – alfetopito

1

你也可以更换线

netvotes = self.votes

netvotes = self.votes or 0

,你现在可以删除if语句。

与其他许多语言一样,它返回非falsy值(None,0,“”)或最后一个值'0'。