过滤iexact错误模型匹配查询不存在

时间:2013-12-31 15:39:01

标签: python django django-views

我正在尝试使用以下命令验证数据库中是否存在值

q = model.objects.filter(field__iexact ='1')

但这会在Django中出错,它会返回此消息:

DoesNotExist at /answer_survey/
Model matching query does not exist

这是整个追溯:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/answer_survey/

Django Version: 1.6.1
Python Version: 2.7.5
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'survey',
 'south',
 'django_reset',
 'chartkick',
 'registration')
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/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/filipeferminiano/Documents/django/panorama/survey/views.py" in answer_survey
  265.                     s = Survey.objects.get(name=cod_survey)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/manager.py" in get
  151.         return self.get_queryset().get(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py" in get
  307.                 self.model._meta.object_name)

Exception Type: DoesNotExist at /answer_survey/
Exception Value: Survey matching query does not exist.

1 个答案:

答案 0 :(得分:1)

您的错误在这里:

s = Survey.objects.get(name=cod_survey)

您的名称中没有包含cod_survey变量...

的记录

添加try / except块以捕获DoesNotExist例外:

try:
    s = Survey.objects.get(name=cod_survey)
except Survey.DoesNotExist:
    s = 'something else...'