I have a User
object and a UserInfo
object which have a one to one relationship. I am just adding the UserInfo
object so some users already have User
objects but not UserInfo
objects. I want to check to see if the User object has a UserInfo object associated with it yet and if not redirect them to a page where I can get some info. I am still new to python and have tried doing an if request.user.user_info:
which throws an exception when it doesn't exist so I ended up doing this:
user = request.user
try:
user.user_info.university
except:
print 'redirect to info page'
which works fine, but I feel like exceptions should be for exceptions and not for if statement substitutes. Is there a better way to do this?
We can use hasattr() function to find if a python object obj has a certain attribute or property. hasattr(obj, 'attribute'): The convention in python is that, if the property is likely to be there, simply call it and catch it with a try/except block.
Django provides a count() method for precisely this reason. Note: If you only want to determine if at least one result exists (and don't need the actual objects), it's more efficient to use exists() .
If you want to determine whether a given object has a particular attribute then hasattr() method is what you are looking for. The method accepts two arguments, the object and the attribute in string format.
I'd say that handling this with exceptions is the pythonic approach. You can do something like this:
try:
# do your thing when user.user_info exists
except AttributeError: # Be explicit with catching exceptions.
# Redirect.
There's a programming concept called it's easier to ask for forgiveness than permission (EAFP)
which is used extensively in Python. We assume that attributes, keys and so forth exist for a given object and catch exceptions when they do not.
Here are some references and SO questions about EAFP.
Python glossary
What is the EAFP principle in Python
EAFP and what is really exceptional
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With