我想通过将字段名称作为字符串传递给函数来获取模型中字段的值,就像使用python字典dict.get(key)
一样,要在模型内部定义一个函数喜欢:
def get(self, key):
key = key.replace('_', '.')
return self.__dict__.get('_prefetch').get(key)
我的问题是,在odoo模型中是否有预定义的函数可以做到这一点,如果不能,那么我该如何以更pythonic的方式做到这一点? 谢谢你。
答案 0 :(得分:1)
Odoo的BaseModel
类已实现__getitem__
1 ,该类允许使用“命名索引”: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
的更多信息