Django-聚合零

时间:2019-03-16 13:02:49

标签: django django-queryset

views.py中包含以下内容:

called = CashFlow.objects.filter(item__slug=itemslug).filter(type='cashin').aggregate(sum=Sum('amount'))['sum']

distributed = CashFlow.objects.filter(item__slug=itemslug).filter(type='cashout').aggregate(sum=Sum('amount'))['sum']

try:
   result = round(-distributed/called * 100,2)
except ZeroDivisionError :
   result = 0

只要其中一个查询返回某些内容,一切就可以正常工作。但是,比方说到目前为止还没有兑现->结果应该为零。但是,我收到以下Typerror:“一元错误的操作数类型-:'NoneType'”

我该如何解决?

非常感谢

2 个答案:

答案 0 :(得分:1)

// 1 (on 'expo red screen of death') undefined is not an object (evaluating '_expo2.default.FileSystem') // 2 (Expo warning; nothing appears on the Surface region) Node#1(DiamondCrop#2), uniform t: no loader found for value, Object { "image": Object { "uri": "http://i.imgur.com/rkiglmm.jpg", }, }, Object { "image": Object { "uri": "http://i.imgur.com/rkiglmm.jpg", }, } // 3 (Expo warning; nothing appears on the Surface region) Node#1(DiamondCrop#2), uniform t: no loader found for value, http://i.imgur.com/rkiglmm.jpg, http://i.imgur.com/rkiglmm.jpg // 4 (Expo warning; nothing appears on the Surface region) Node#1(DiamondCrop#2), uniform t: no loader found for value, http://i.imgur.com/rkiglmm.jpg, http://i.imgur.com/rkiglmm.jpg 添加到TypeError的例外中

except

答案 1 :(得分:1)

在尝试/添加之前添加此内容

if distributed is None:
    distributed = 0

或在CashFlow查询之后添加or 0

distributed = (CashFlow.objects
    .filter(item__slug=itemslug)
    .filter(type='cashout')
    .aggregate(sum=Sum('amount'))['sum']) or 0

called执行相同操作。