2016-11-22 44 views
0

我正在通過編碼爲企業家做一些Django實踐。 這是代碼:Django Query的問題

from django.shortcuts import render, get_object_or_404 
from django.http import HttpResponse 
from django.views import View 

from .models import KirrURL 

def kirr_redirect_view(request,shortcode=None,*args,**kwargs): 

    #Method 1: 

    obj = get_object_or_404(KirrURL, shortcode__iexact=shortcode) 
    obj_url = obj.url 

    #Method 2: 

    qs = KirrURL.objects.filter(shortcode__iexact=shortcode) 
    if qs.exists() and qs.count() == 1: 
     obj = qs.first() 
     obj_url = obj.url 

    return HttpResponse("Hello : {sr}".format(sr=obj_url)) 

我做什麼是我得到一些話,從URL,並將其傳遞到kirr_redirect_view,並USDE查詢來獲取數據並返回一些單詞。 該網站介紹了兩種方法來做到這一點。第二個工作正常。當我更改爲第一種方法。該方法突然出現錯誤,即使我傳遞了正確的關鍵詞,我仍然從頁面獲取404。

+5

如果選項2是您正在使用的網站推薦的,則需要立即找到其他教程。這完全沒有理由的三個查詢。 –

回答

2

按照Django的文檔:

get_object_or_404()

調用的get()在一個給定的模型管理器,但它提出了HTTP404而不是模型的DoesNotExist例外。

因此,如果沒有匹配的記錄,get_object_or_404將提高404: content not found

在第二種方法中,如果沒有匹配,即您的if失敗,仍然會發送HttResposne對象,該對象的默認狀態爲200: OK

總之,您的KireURL模型沒有匹配的記錄shortcode__iexact=shortcode

+0

我的意思是,當我輸入相同的shortcode參數,這是建立在我的數據庫中,第一個方法失敗,第二個很好。我不知道爲什麼。我認爲它應該得到相同的結果。或者我應該給一些額外的代碼供您檢查? – honesty1997

0

第二種方法顯示你的網址或只是沒有提出錯誤?過濾器永遠不會引發任何異常,以及它看起來像多於一個具有相同短代碼的對象,或者沒有任何異常並且如果condition.That是爲什麼get_object_or_404()引發異常。

+0

我現在再次在shell中運行它,當get_object_or_404保持失敗時,我可以使用get方法得到確切的結果...... – honesty1997

0

我在這裏添加一些信息。這是我使用Python shell運行代碼時得到的結果。

>>> from shortener.models import KirrURL 
>>> from django.shortcuts import get_object_or_404 
>>> obj = get_object_or_404(KirrURL,shortcode='pric3e') 

Traceback (most recent call last):File"/Users/phil/Desktop/django110/lib/python3.5/site 
packages/django/shortcuts.py", line 85, in get_object_or_404 
return queryset.get(*args, **kwargs) 
File "/Users/phil/Desktop/django110/lib/python3.5/site-packages/django/db/models/query.py", line 385, in get 
self.model._meta.object_name 
shortener.models.DoesNotExist: KirrURL matching query does not exist. 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
File "<console>", line 1, in <module> 
File "/Users/phil/Desktop/django110/lib/python3.5/site-packages/django/shortcuts.py", line 93, in get_object_or_404 
raise Http404('No %s matches the given query.' % queryset.model._meta.object_name) 
django.http.response.Http404: No KirrURL matches the given query. 

>>> obj = KirrURL.objects.get(shortcode='pric3e') 
>>> obj 
<KirrURL: http://google.com> 
>>> obj.id 
1 
>>> obj.url 
'http://google.com'