我做对数据库的查询,我想如果查询返回无关的东西,但我得到一个错误:Django无法找到对象时会返回什么结果?
user = User.objects.get(name=Jack)
if (user == NULL):
# something
我得到一个用户匹配的查询不存在。
我做对数据库的查询,我想如果查询返回无关的东西,但我得到一个错误:Django无法找到对象时会返回什么结果?
user = User.objects.get(name=Jack)
if (user == NULL):
# something
我得到一个用户匹配的查询不存在。
它throws an exception。也许你应该尝试catching it。
Django不会'返回'任何东西,它会抛出一个错误,所以你没有得到你的if测试。
而是围绕该代码在尝试捕捉,像这样
try:
user = User.objects.get(name="Jack")
except User.DoesNotExist:
user = None
编辑:哎呀,蟒蛇让我每次;)
>>>空 回溯(最近通话最后一个): 文件“
丹科,我忘记一些蟒蛇怪癖有时。 – addisonj 2011-06-15 23:12:54
评论太短:) – 2011-06-15 23:14:56
你将要使用这样的事情。 https://docs.djangoproject.com/en/1.3/ref/models/querysets/#get
try:
user = User.objects.get(name="Jack")
except User.DoesNotExist:
print "User does not exist"
如果你只是去404页,你可能需要使用以下https://docs.djangoproject.com/en/1.3/topics/http/shortcuts/#get-object-or-404
from django.shortcuts import get_object_or_404
user = get_object_or_404(User, name="Jack")
如果你想显示如果对象不存在404错误,有一个快捷方式功能[get_object_or_404](https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#get-object-or-404)。 – Corey 2011-06-15 23:10:11