我正在使用Django教程学习Python,我有这段代码
poll = Poll.objects.get(pk = poll_id)
当poll_id不在数据库中时,我得到一个DoesNotExist异常,这很好,因为教程告诉我要执行以下操作:
try:
poll = Poll.objects.get(pk = poll_id)
except Poll.DoesNotExist:
raise Http404
我的问题是:如果我没有帮助我的教程,考虑到下面的堆栈跟踪,我怎么会知道DoesNotExist异常是Poll的一部分?
(即我的猜测是放'除了DoesNotExist:',这会告诉我:“全局名称'DoesNotExist'未定义”)
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/3/
Django Version: 1.6.2
Python Version: 2.7.2
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/tom/Documents/dev/django-test/mysite/polls/views.py" in detail
26. poll = Poll.objects.get(pk = poll_id)
File "/Library/Python/2.7/site-packages/django/db/models/manager.py" in get
151. return self.get_queryset().get(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/db/models/query.py" in get
307. self.model._meta.object_name)
Exception Type: DoesNotExist at /polls/3/
Exception Value: Poll matching query does not exist.
python的新手。我显然错过了一些明显的东西。
答案 0 :(得分:4)
你不会知道;你必须查看project documentation或抛出异常的代码。
请注意Model.DoesNotExist
引用是一种便利,因此您也不必导入异常。你不会从抛出异常的代码中推断出这一点。这个特殊的Django异常对象是每个模型定制的django.core.exceptions.ObjectDoesNotExist
的子类。
通常,您可以捕获Exception
并查看捕获的异常的模块:
except Exception as e:
print type(e), type(e).__module__
这将告诉您定义异常的模块,为您提供将来从那里导入它的选项。