【问题标题】:unsupported operand type(s) for +: 'NoneType' and 'NoneType'+ 不支持的操作数类型:“NoneType”和“NoneType”
【发布时间】:2014-07-06 03:36:25
【问题描述】:

我该如何处理这个错误,它让我发疯:

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

还有

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

我明白它告诉我的(我认为)所以这是我写的代码来尝试和它战斗

查看:

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))

我想我正在做的是将它们的值设置为 0,然后再将其相加,如果它碰巧没有作为值。是否有另一种方法来处理这个问题,以便当其中一个确实没有出现时,它被设置为零以便可以添加。此外,当 BOTH 都为 none 时,可以将它们设置为 0,以便可以添加它们。

【问题讨论】:

  • 先添加print intprint team,看看哪些值是None。另外,这是您的实际 视图吗? stacktrace + 确切的代码会有所帮助
  • 是的,这是我的实际观点,所有之后都是回报。我不确定堆栈跟踪是什么。他们中的任何一个都可能是 None 因为链从两个查询中获取值,他们不会总是返回一些东西
  • stacktrace 是您在错误屏幕上看到的(其中提到了问题的行号等)

标签: django django-models django-errors django-aggregation


【解决方案1】:

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

check = 0
ind = None
team = None

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

有更优雅的方法可以做到这一点,但如果你只是将 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

【讨论】:

  • 先生,因为你,我觉得自己更聪明了。我希望我曾想过这样做,而不是我最终做的事情(如果它不存在则创建一个虚拟实例(我还是新的))。您的方式在数据库上可能更有效,所以我会使用它,谢谢。我不知道 elif 只有在 , if 为假时才会发生。
  • 是的,elif 是 Python 的“else, if”的缩写形式——所以“else”部分必须为真(意味着原始的 if 为假),然后才能评估第二个 if .
猜你喜欢
  • 2015-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-22
  • 1970-01-01
  • 2011-11-22
  • 2016-09-07
相关资源
最近更新 更多