If you don't want to use exception (which I do when doing something
similar). You can use filter and then check the length of the array
returned.
def my_view( request , pk ):
obj = Class.objects.filter( pk = pk)
if len(obj) != 1:
return bad_key_view
obj = obj[0]
# Do something with obj and return a suitable response.
/J
On Fri, Apr 9, 2010 at 11:54 PM, Joakim Hove <[email protected]> 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
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to [email protected].
> To unsubscribe from this group, send email to
> [email protected]<django-users%[email protected]>
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.