0

How can I handle this error, its driving me crazy:

unsupported operand type(s) for +: 'NoneType' and 'NoneType'

Also

unsupported operand type(s) for +: 'Float' and 'NoneType'

I get what its telling me (I think) so this is the code I wrote to try and battle it

View:

session = request.session._session_key
ind = signedup.objects.filter(sessionid = session)
team = team_signup.objects.filter(sessionid = session)
combine = list(chain(ind, team))


check = signedup.objects.filter(sessionid = session).count() + team_signup.objects.filter(sessionid = session).count()
ind = signedup.objects.filter(sessionid = session).aggregate(Sum ('price'))['price__sum']
team = team_signup.objects.filter(sessionid = session).aggregate(Sum ('price'))['price__sum']
if check == 0:
  carttotal = 0.00
elif ind == None:
  ind = 0.00
elif team == None:
  team = 0.00

carttotal = ind + team


return render_to_response("cart.html",locals(),context_instance = RequestContext(request))

I figured what I was doing was setting their values to 0 before adding it up if it happened to be come up with none as a value. Is there another way to handle this so that when one of them does come up none, it gets set to zero so it can be added. Also when BOTH come up to none they can be set to 0 so that they can be added.

4

1 回答 1

1

部分问题可能是 if/elif 逻辑。请记住,只有当第一个 if 语句注册为 false 时,elif 才会运行。所以,想象一下这个场景:

check = 0
ind = None
team = None

在这种情况下,首先发生的事情是 Carttotal 被设置为 0。然后,由于第一个 if 为真(检查为 0),剩余的 elif 不会运行,并且 ind + team 尝试被添加,即使它们没有从无更改。

有更优雅的方法可以做到这一点,但如果你只是将 elifs 更改为 ifs,它应该可以正常工作。但是,那里有一些冗余,并通过使用三级运算符将逻辑缩短几行

ind_query = signedup.objects.filter(sessionid = session)
ind = ind_query.aggregate(Sum ('price'))['price__sum'] if ind_query else 0

team_query = team_signup.objects.filter(sessionid = session)
team = team_query.aggregate(Sum ('price'))['price__sum'] if team_query else 0

carttotal = ind + team
于 2014-07-06T05:32:46.123 回答