[英]Django: how to pass **kwarg to annotate()
我是 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 進行注釋的任何幫助
您正在傳遞字符串“Sum(blah)”,因此出現錯誤。
FList['total_size'] = Sum(FName)
但實際上根本沒有理由在這里使用 kwargs:
data=Department.objects.annotate(total_size=Sum(FName))
簡化..
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))
我希望這可以幫助你走上這條路
對於那些真正想通過kwarg
進行注釋的人,可能因為它是動態定義的,你必須執行以下操作:
annotate_filters = {
'sum_foo': Count('foo', distinct=True),
}
if foo:
annotate_filters['sum_foo'] = Count('bar', distinct=True)
Foo.objects.annotate(**annotate_filters)
通過這種方式,您可以管理不同的條件並將它們傳遞給注釋函數。
快樂編碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.