0

I'm trying to get an object, if it existed ok if not then something else and so on. Is it correct to do the following? I've heared that exceptions are expensive and shuold be avoided, is that correct?

try:
   user = User.objects.get(user=id)
except ObjectDoesNotExist:
   try:
       user = User.objects.get(email=id)
   except ObjectDoesNotExist:
       try:
        # ...

finally:
    # do the final thing

2 Answers 2

1

They are somewhat expensive, but certainly not too expensive to use when needed. I'd be more concerned about hammering the database with multiple queries You can avoid both problems by getting the results for all possible fields back in one query.

from django.contrib.auth.models import User
from django.db.models import Q
user = User.objects.filter(Q(user=id) | Q(email=id) | [...])[0]

This relies on django's Q-objects, which allow you to create conditions joined together in more complex ways than the usual AND joins that you usually get when building filters. If you aren't concerned about the possibility of getting multiple objects back, you can still use the get() method like you did in your example.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm a newbie and I didn't knew about that, thanks a lot for your help and time.
1

The cost of a try/except is explained here: cost-of-exception-handlers-in-python

I suggest to catch things that should not happen or only happen rarely (real exceptions) with a try/except and more common situations with conditions. Especially in a case like a Model.objects.get() where the underlying sql returns an empty list that wouldn't raise an exception if called as a filter.

users = User.objects.filter(user=id)[:1]
user = users and users[0]

1 Comment

Thanks alot for the second time today, it was quite helpful despite I used the other one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.