I would like to get an attribute of mongoengine model object but it’s missing (how it’s often in mongo):
unit.city gives me
unit.get('city') says that
'Unit' object has no attribute 'get' and I can’t find any appropriate method by
So I have to use standard python statement:
city = unit.city if 'city' in unit else None
That is a bit complex for just a
get operation, because I have many transformations of that kind.
And so I wonder if there is any universal method for getting attribute value or some default value (if attribute doesn’t exist) — such as
city = unit.get('city') # None # or city = unit.get('city', 'Moscow') # 'Moscow'
I would define my own function
get but I’m interested if there is any in standard libraries. And yet,
from operation import getitem doesn’t able to do that.
I use python 2, by the way.
getattr(object, name[, default]):
city = getattr(unit, 'city', 'Moscow')
city = getattr(unit,'city','Moscow')
Other approach is
try: city = unit.city except AttributeError: city = None
The second is argubly more pythonic. However when you are dealing with databases. It’s better to use an ORM and avoid this sort of thing all together.