本文介绍了TypeError:'DoesNotExist'对象不可调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这并不总是这个代码块,但这是最近的。似乎是随机的,有什么想法?

It's not always this code chunk but this is the most recent. It seems to be random, any thoughts?

try:
    u = User.objects.get(email__iexact=useremail)
except User.DoesNotExist:
    ...

随机抛出此错误。

File "/srv/myapp/registration/models.py", line 23, in get_or_create_user
  u = User.objects.get(email__iexact=useremail)

File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 132, in get
  return self.get_query_set().get(*args, **kwargs)

File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 349, in get
  % self.model._meta.object_name)

TypeError: ‘DoesNotExist’ object is not callable


推荐答案

正如Chris在上述评论中所说,您的代码段是有效的。您的代码中还有其他地方,您可能会错误地捕获异常。

As Chris says in the comments above, your snippet is valid. Somewhere else in your code, you may be catching exceptions incorrectly.

您可能会有以下情况:

try:
    do_something()
except User.MultipleObjectsReturned, User.DoesNotExist:
    pass

而不是:

try:
    do_something()
except (User.MultipleObjectsReturned, User.DoesNotExist):
    pass

没有括号中,except语句等同于以下Python 2.6+

Without the parentheses, the except statement is equivalent to the following in Python 2.6+

except User.MultipleObjectsReturned as User.DoesNotExist:

User.MultipleObjectsReturned 异常的实例覆盖 User.DoesNotExist

当相同的进程稍后处理不同的请求时,您将获得
TypeError ,因为您的代码正在尝试调用已替换 User.D的异常实例oesNotExist

When the same process handles a different request later on, you getthe TypeError because your code is trying to call the exception instance which has replaced User.DoesNotExist.

这篇关于TypeError:'DoesNotExist'对象不可调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 10:18