我做對數據庫的查詢,我想如果查詢返回無關的東西,但我得到一個錯誤: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