Question:
The obj
object is an instance of some kind of django model. Let's say it has a prop
field, which is supposed to be associated with another model, but could also be None
. My task is to write to the var
variable the target
field of the second linked model.
var = obj.prop.target
If the prop
field is equal to None
, then everything will break, since None
does not have a target
field. In this case, I want to set the var
variable to None
. Basically I can do it like this
try:
var = obj.prop.target
except AttributeError:
var = None
Is there some other way to do this, like setdefault
for dictionaries?
Answer:
Use the built-in function getattr(object, name[, default])
:
var = getattr(obj.prop, "target", None)
getattr(object, name[, default])
Return the value of the named attribute of object. name must be a
string. If the string is the name of one of the object’s attributes,
the result is the value of that attribute. For example,getattr(x, 'foobar')
is equivalent tox.foobar
. If the named attribute does not
exist, default is returned if provided, otherwiseAttributeError
is
raised.