匹配查询不存在
我正在研究一个Django项目,并且出现这个错误,“状态匹配查询不存在”。 为什么发生这种情况? 国家在模特商店,你能解释我这个错误以及如何解决它吗?
谢谢。 浏览次数:
def Test(request):
stores = Store.objects.all()
data = []
for store in stores:
data.append({
'id': store.id,
'name': store.name,
'address': store.address,
'state': store.state,
})
return HttpResponse(json.dumps(data), 'application/json')
楷模:
class State(models.Model):
name = models.CharField(max_length=255)
shortname = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class City(models.Model):
name = models.CharField(max_length=255)
state = models.ForeignKey(State)
def __unicode__(self):
return self.name
class Store(models.Model):
name = models.CharField(max_length=255, null=True, blank=True)
address = models.CharField(max_length=255, blank=True, null=True)
lon = models.FloatField(blank=True, null=True)
lat = models.FloatField(blank=True, null=True)
state = models.ForeignKey(State)
city = models.ForeignKey(City)
def __unicode__(self):
return self.name
追溯:
环境:
请求方法:GET请求URL:http://127.oo1:8000 / posts / Test /
Django版本:1.7.1 Python版本:2.7.6安装的应用程序:('django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django .contrib.messages','django.contrib.staticfiles','clients','cobrands','core','posts','bootstrapform','rest_framework')Installed Middleware :('django.contrib.sessions.middleware .SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.auth.middleware.SessionAuthenticationMiddleware','django .contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:在get_response 111中的文件“/home/tabzz/c-dev/local/lib/python2.7/site-packages/django/core/handlers/base.py”。response = wrapped_callback(request,* callback_args,** callback_kwargs)测试34中的“/home/tabzz/c/posts/views.py”文件。'state':store.state,File“/home/tabzz/c-dev/local/lib/python2.7/site- packages / django / db / models / fields / related.py“in get 572. rel_obj = qs.get()File”/home/tabzz/c-dev/local/lib/python2.7/site-packages/django/ db / models / query.py“in get 357. self.model._meta.object_name)
异常类型:DoesNotExist at / posts / Test / Exception值:状态匹配查询不存在。
它看起来像你的数据库中没有state
的Store模型。 当你尝试在这里访问state
:
data.append({
'id': store.id,
'name': store.name,
'address': store.address,
'state': store.state,
})
Django抛出一个错误,因为state
是Store
上的一个ForeignKey
,当你用store.state
访问它时,它必须查找它。 如果state
为空,并且您没有将ForeignKey
设置为允许None
值为null=True
,则Django将引发DoesNotExist
异常。