Django-类型错误“不可下标”

时间:2019-03-14 19:32:31

标签: django django-queryset typeerror

我正在尝试创建一个包含多个计算的列表。接下来的想法是将其呈现在模板中。

这是我到目前为止所拥有的:

views.py:

def calculation(request, itemslug):

#All the Values ordered chronologically:  

values = Value.objects.filter(item__slug=itemslug).order_by('date')

dates = []
results =[]

#Create a list consisting of the dates

for value in values:
    a = value.date
    dates.append(a)

#Peform a calculation per date

for date in dates:

    latestvalue = Value.objects.filter(item__slug=itemslug).get(date=date)['amount']
    paidup = CashFlow.objects.filter(item__slug=itemslug).filter(date__lt=date).filter(type='cashin').aggregate(sum=Sum('amount'))['sum']

    try:
       result = round(latestvalue/paidup * 100,2)
    except ZeroDivisionError :
       result = 0

    results.append(result)

return render(request, 'overview/detail.html',
    {
    'result':results,
    })

不幸的是,我收到TypeError:“值对象不可下标” +可能是我的代码中还有其他错误。.非常感谢您的关注!!

谢谢

1 个答案:

答案 0 :(得分:1)

如何简化一下:

    latestvalue = Value.objects.get(item__slug=itemslug, date=date).amount
    paidup = (CashFlow.objects
        .filter(item__slug=itemslug, date__lt=date, type='cashin')
        .aggregate(sum=Sum('amount'))['sum'])