我是django框架和Python的新手。我要求对用户在运行时选择的字段进行聚合
class Department(models.Model):
code = models.CharField(max_length=10, primary_key=True)
size = models.IntegerField(blank=True, null=True)
budget = models.IntegerField(blank=True, null=True)
我想通过执行类似以下的操作,选择使用** kwarg执行大小,预算或两者的总和
from django.db.models import Avg, Count, Sum
# let Fname has the name of the field to sum on, set by a user input
FName='size'
FList={}
# problem in passing the following
FList['total_size']="Sum(' "+FName+" ')"
data=Department.objects.annotate(**FList)
但我收到以下错误
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "c:\python34\lib\site-packages\django\db\models\query.py", line 802, in annotate
is_summary=False)
File "c:\python34\lib\site-packages\django\db\models\sql\query.py", line 1030, in add_aggregate
field_list = aggregate.lookup.split(LOOKUP_SEP)
AttributeError: 'str' object has no attribute 'lookup'
从列表中的讨论中暗示,在密钥,值对
中无法识别Sum赞赏将** kwarg传递给注释的任何帮助
答案 0 :(得分:1)
你传递字符串“Sum(blah)”,因此错误。
FList['total_size'] = Sum(FName)
但实际上没有理由在这里使用kwargs:
data=Department.objects.annotate(total_size=Sum(FName))
答案 1 :(得分:0)
简化..
from django.db.models import Avg, Count, Sum
# let Fname has the name of the field to sum on, set by a user input
FName='size'
data=Department.objects.annotate(total_size=Sum(FName))
由于FName
是一个字符串,因此您不需要用引号将其包装起来。如果你需要运行一个不同的功能,比如avg等...
from django.db.models import Avg, Count, Sum
# let Fname has the name of the field to sum on, set by a user input
FName='size'
function_t = Sum # or Avg, or Count
data=Department.objects.annotate(total_size=function_t(FName))
我希望这可以帮助你走上正轨