Introduction
It's strange to see the get_object_or_404 function today when I look at the official Django document. This is mainly derived from its function, if the object to be queried
The object is returned, and if the object does not exist then it is reported 404 Not Found, but 404 Not Found is not its return value, and Django directly returns
404 pages, This feeling is more strange.
1, a failure to simulate the get_object_or_404
fromDjango.shortcutsImportRender fromDjango.httpImportHttp404,httpresponsedeffun_get_object_or_404 (pk=None):ifPK = = 1: return1Else: returnHttpResponse ('object is not found ...')defIndex (Request): obj=fun_get_object_or_404 ()returnHttpResponse ("object is {0}". Format (obj))
Let's take a look at the results of the view.
From the returned content we can see that the treatment of httpresponse is not the same as in middleware, middleware as long as it is to meet the return HttpResponse such
The content will immediately return to the response object to the browser; how did that get_object_or_404 happen?
2, the official implementation of GET_OBJECT_OR_404
defget_object_or_404 (Klass, *args, * *Kwargs):"""Use get () to return a object, or raise a Http404 exception if the object does not exist. Klass may be a Model, Manager, or QuerySet object. All other passed arguments and keyword arguments is used in the Get () query. Like with Queryset.get (), multipleobjectsreturned are raised if more than one object is found. """Queryset=_get_queryset (Klass)Try: returnQueryset.get (*args, * *Kwargs)exceptAttributeerror:klass__name= Klass.__name__ ifIsinstance (Klass, type)ElseKlass.__class__.__name__ RaiseValueError ("First argument to get_object_or_404 () must is a Model, Manager," "or QuerySet, not '%s '."%klass__name)exceptqueryset.model.DoesNotExist:RaiseHttp404 ('No%s matches the given query.'% queryset.model._meta.object_name)
This is just raise a Http404, notice here is raise instead of return stating that Http404 is not a subclass of HttpResponse, it should be an exception.
3, the official implementation of HTTP404
class Http404 (Exception): Pass
Scorching! The goods on a simple Exception subclass, not HttpResponse subclasses, there is a point to note do not want to use raise Exception (' xxx ') way to
Replacing the Http404 is not feasible, so the words will be directly error.
----
Django Http404 Detailed