Django,匹配查询不存在

我是Django的新手。当我在pycharm运行命令python manage.py runserver,我得到这样Django,匹配查询不存在

2017-12-03 05:09:56,952 - INFO - server - Listening on endpoint 

tcp:port=8000:interface=127.0.0.1

Internal Server Error:/

Traceback (most recent call last):

File "/Users/mac/anaconda/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in innerresponse = get_response(request)

File "/Users/mac/anaconda/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request)

File "/Users/mac/anaconda/lib/python3.6/site-packages/channels/handler.py", line 243, in process_exception_by_middleware

return super(AsgiHandler,self).process_exception_by_middleware(exception, request)

File "/Users/mac/anaconda/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/mac/PycharmProjects/590/flightmate/webapp/views.py", line 180, in index airlines = RecordSet.objects.get(name="airline")

File "/Users/mac/anaconda/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method

return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/Users/mac/anaconda/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name

webapp.models.DoesNotExist: RecordSet matching query does not exist.

错误消息的models.py的代码是:

from __future__ import unicode_literals 

import uuid

import datetime

from django.db import models

class RecordSet(models.Model):

name = models.CharField(max_length=512)

value = models.TextField()

def __unicode__(self):

return "{0}: {1}".format(self.name, self.value)

models.py的父目录的目录webapp。任何建议表示赞赏,谢谢!

回答:

正如你可以回溯看到,这个问题是这样的:

airlines = RecordSet.objects.get(name="airline") 

您检索单个对象与get()并且由于它不存在,它返回DoesNotExist例外。这也是Django文档在小节Retrieving a single object with get()

明确提到如果没有结果匹配查询,获得()将引发 DoesNotExist例外。此例外是正在执行查询的 类的一个属性 - 因此在上面的代码中,如果 没有主键为1的Entry对象,则Django将引发 Entry.DoesNotExist。

要么使用filter()get()try ... except声明。如果您知道只有一个对象与您的查询匹配,则应该使用get(),否则使用filter()

以上是 Django,匹配查询不存在 的全部内容, 来源链接: utcz.com/qa/259584.html

回到顶部