我希望通过将字段名称作为字符串传递给函数来获取模型中字段的值,因为它是使用python字典dict.get(key)
完成的,为此我在模型中定义了一个函数,如:
def get(self, key):
key = key.replace('_', '.')
return self.__dict__.get('_prefetch').get(key)
我的问题是,在odoo模型中是否有预定义的功能可以做到这一点,如果没有,我怎么能以更加pythonic的方式做到这一点?提前致谢。
Odoo的BaseModel
类实现了__getitem__
1,允许使用“命名的indeces”:recordset['field_name']
来自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)
因此,在记录集上,将读取第一个记录的属性。尽可能尝试在单身人士身上使用它。
1有关通用类型click here的更多信息