Reputation: 419
I want to get the value of a field in a model, by passing the field name as string to a function, as it's done with a python dictionary dict.get(key)
, to do that I defined a function inside the model like:
def get(self, key):
key = key.replace('_', '.')
return self.__dict__.get('_prefetch').get(key)
my question is, is there a predefined function in odoo models that can do that, if not, how can I do that in a more pythonic way ? Thank's in advance.
Upvotes: 1
Views: 2434
Reputation: 14768
Odoo's BaseModel
class has implemented __getitem__
1 which allows usage of "named indeces": recordset['field_name']
From Odoo 12.0 odoo.models.BaseModel:
def __getitem__(self, key):
""" If ``key`` is an integer or a slice, return the corresponding record
selection as an instance (attached to ``self.env``).
Otherwise read the field ``key`` of the first record in ``self``.
Examples::
inst = model.search(dom) # inst is a recordset
r4 = inst[3] # fourth record in inst
rs = inst[10:20] # subset of inst
nm = rs['name'] # name of first record in inst
"""
if isinstance(key, pycompat.string_types):
# important: one must call the field's getter
return self._fields[key].__get__(self, type(self))
elif isinstance(key, slice):
return self._browse(self._ids[key], self.env)
else:
return self._browse((self._ids[key],), self.env)
So on recordsets the first record's attribute will be read. Try to use it on singletons if possible.
1 for further information on generic types click here
Upvotes: 1