On Apr 9, 10:54 pm, Joakim Hove <joakim.h...@gmail.com> wrote:
> Hello,
>
> I have something I would presume was a very common pattern. I have a
> view which gets a primary-key (from the user) as second argument:
>
> def my_view( request , pk ):
>      obj = Class.objects.get( pk = pk)
>      # Do something with obj and return a suitable response.
>
> Now, of course I would like to check whether the object identified by
> 'pk' is in the database, and return a suitable error message if that
> fails; I was halfway expecting to find a "has_key() / exists() / ..."
> method, but it seems the only way to handle this gracefully is by
> catching the DoesNotExist exception?
>
> I have never really got very friendly with exceptions, I tend to
> consider them as something exceptional which "should not" happen,
> whereas the fact that the database does not contain a particular key
> is in my opinion something quite ordinary and not by any means
> "exceptional".
>
> Or maybe I am misunderstanding roally here?
>
> Joakim

Although I agree with the other posts that there isn't anything
exceptional about exceptions in Python, there is a shortcut for
exactly this pattern: get_object_or_404. See the documentation:
http://docs.djangoproject.com/en/dev/topics/http/shortcuts/#get-object-or-404
--
DR.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to