设置默认值的几种方式
- context中设置default_字段名
- 设置-技术-用户定义的默认值中配置(存储在 ir.default模型中)
- 字段的default属性
- 父模型中的默认值
常在瞬态模型中重写default_get设置默认值
界面点击创建按钮后发起一个onchange请求,onchange方法调用default_get返回默认值 odoo15/models.py
代码语言:javascript复制 @api.model
def default_get(self, fields_list):
""" default_get(fields_list) -> default_values
Return default values for the fields in ``fields_list``. Default
values are determined by the context, user defaults, and the model
itself.
:param list fields_list: names of field whose default is requested
:return: a dictionary mapping field names to their corresponding default values,
if they have a default value.
:rtype: dict
.. note::
Unrequested defaults won't be considered, there is no need to return a
value for fields whose names are not in `fields_list`.
"""
# trigger view init hook
self.view_init(fields_list)
defaults = {}
parent_fields = defaultdict(list)
ir_defaults = self.env['ir.default'].get_model_defaults(self._name)
for name in fields_list:
# 1. look up context
key = 'default_' name
if key in self._context:
defaults[name] = self._context[key]
continue
# 2. look up ir.default
if name in ir_defaults:
defaults[name] = ir_defaults[name]
continue
field = self._fields.get(name)
# 3. look up field.default
if field and field.default:
defaults[name] = field.default(self)
continue
# 4. delegate to parent model
if field and field.inherited:
field = field.related_field
parent_fields[field.model_name].append(field.name)
# convert default values to the right format
#
# we explicitly avoid using _convert_to_write() for x2many fields,
# because the latter leaves values like [(Command.LINK, 2),
# (Command.LINK, 3)], which are not supported by the web client as
# default values; stepping through the cache allows to normalize
# such a list to [(Command.SET, 0, [2, 3])], which is properly
# supported by the web client
for fname, value in defaults.items():
if fname in self._fields:
field = self._fields[fname]
value = field.convert_to_cache(value, self, validate=False)
defaults[fname] = field.convert_to_write(value, self)
# add default values for inherited fields
for model, names in parent_fields.items():
defaults.update(self.env[model].default_get(names))
return defaults