Reputation: 6831
If i have dictionary the this works fine
value = d.get(key, "empty")
But if d
is my django model object
then i get this
object has no attribute 'get'
How can i fix that. I want have same behaviour like dict to get empty if key does not exist
Upvotes: 1
Views: 87
Reputation: 45575
Use getattr()
:
value = getattr(d, key, "empty")
Another option is to direct access to the object's __dict__
:
value = d.__dict__.get(key, "empty")
But I suggest to use the getattr()
.
UPDATE: Note that getattr(some_dict, key)
is not the same as the some_dict.get(key)
. getattr()
gets the object's attribute but not the value of the dict.
Upvotes: 6