聚合函数返回AttributeError的:“总”对象有没有属性“查找”

问题描述 投票:1回答:4

我想出来的聚合功能,我得到这个奇怪的结果(最新官方的Django 1.2版本)。这里的模型:

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'
django django-queryset
4个回答
4
投票

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

你对你的控制台会话的37行。试着重新开始,from django.db.models import Sumfrom myproject.myapp.models import Reputation,然后查询。


5
投票

确保导入正确的Sum

from django.db.models import Sum

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


0
投票

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

错误:

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

对:

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

我的一个愚蠢的错误,但认为我会记录在这里的情况下,它可以帮助别人。


0
投票

这是不完全的问题是什么,但我遇到的几乎F使用annotate同样的错误(没有属性“查找”)。进口是正确的,但its use in annotate在Django 1.8加入,而我使用Django 1.7。你需要,如果您还使用旧版本的Django转而使用filter

© www.soinside.com 2019 - 2024. All rights reserved.