2011-03-17 58 views
1

我正在尝试聚合函数,并得到这个奇怪的结果(最新的官方Django 1.2版本)。 这里的模型:聚合函数返回AttributeError:'总和'对象没有属性'查找'

class Reputation(models.Model): 
    user = models.ForeignKey(User) 
    modifier = models.IntegerField() 
    activity = models.ForeignKey(Activity) 

这就是我得到:

In [37]: Reputation.objects.aggregate(r=Sum('modifier')) 
--------------------------------------------------------------------------- 
AttributeError       Traceback (most recent call last) 

C:\Data\Development\django_projects\oko\lib\site-packages\django\db\models\manager.pyc in aggregate(self, *args, **kwargs) 
    142 
    143  def aggregate(self, *args, **kwargs): 
--> 144   return self.get_query_set().aggregate(*args, **kwargs) 
    145 
    146  def annotate(self, *args, **kwargs): 

C:\Data\Development\django_projects\oko\lib\site-packages\django\db\models\query.pyc in aggregate(self, *args, **kwargs) 
    315   for (alias, aggregate_expr) in kwargs.items(): 
    316    query.add_aggregate(aggregate_expr, self.model, alias, 
--> 317     is_summary=True) 
    318 
    319   return query.get_aggregation(using=self.db) 

C:\Data\Development\django_projects\oko\lib\site-packages\django\db\models\sql\query.pyc in add_aggregate(self, aggregate, model, alias, is_summary) 
    929   """ 
    930   opts = model._meta 
--> 931   field_list = aggregate.lookup.split(LOOKUP_SEP) 
    932   if len(field_list) == 1 and aggregate.lookup in self.aggregates: 
    933    # Aggregate is over an annotation 

AttributeError: 'Sum' object has no attribute 'lookup' 
+2

你从哪里输入'Sum'? – DrMeers 2011-03-17 22:04:27

+0

好问题;看到我的答案,下面。 – LaundroMat 2011-03-17 22:32:06

回答

4

的事实,你的职位是通过谷歌搜索的错误消息的唯一一提,那我可以重现来看你通过在聚合函数中使用一个名为Sum的随机类发生错误,我认为你的代码中有一个Sum的本地定义。

您正处于控制台会话的第37行。尝试重新开始,from django.db.models import Sum,from myproject.myapp.models import Reputation,然后查询。

+0

哦,我没有那个。我相信这会帮助人们搜索! – 2011-03-17 22:33:54

0

我通过不包括注释IE中的聚合功能得到了同样的错误

错误:

Person.objects.annotate(ave_score='starred_in__score') 

权:

Person.objects.annotate(ave_score=Avg('starred_in__score')) 

我的一个愚蠢的错误,但以为我会在这里记录它,以防其他人帮助。

5

确保导入正确的Sum

from django.db.models import Sum 

如果导入django.db.models.sql.aggregates.Sum,你会继续看到错误。

相关问题