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 django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Exceptions (despite the name) are absolutely *not* "exceptional" in
Python; they're the standard idiom for handling all sorts of things.
The "Pythonic" idea isn't "Look Before You Leap" (check first, then
act); it's instead "Easier to Ask Forgiveness than Permission" (try to
do something, and handle failure if it does happen).
Love your exceptions; they're friendly (and quite useful) beasts.
http://plope.com/Members/chrism/exceptions_arent_errors/view
The only arguably exceptional part is that ideally the ORM would raise
a plain KeyError exception instead of a custom exception when a key
look-up fails ...
It makes a difference if you are likely to find an object or not - at
least in terms of performance.
If you are expecting to find an object, (and only one), the setup of a
try: except: clause is minimal, but if you are not finding an object
more often than not, it turns out to be much slower to have the
exception raised.
Having said that, the cost of having two DB queries may overcome that
anyway: len(queryset) followed by queryset.get() is probably going to
hit the database twice. A better solution would be to do a
queryset.all(), see if the length is 1, and then get the first value
by index 0.
Matt.
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.
if Class.objects.filter(pk=pk).count() == 0:
# Do object doesn't exist stuff
else:
# Do object does exist stuff
--
G
On Apr 9, 11:44 pm, johan sommerfeld <johan.sommerf...@gmail.com>
wrote:
> > django-users...@googlegroups.com<django-users%2Bunsubscribe@google groups.com>