为什么自定义字段无法保存在创建模式下,它保存在 odoo 的写入模式下?

Why Custom Field could not saved in create mode, it saved on write mode in odoo?

我在产品模板模型中添加了零件编号字段

partnumber = fields.Char(
        'Part Number', compute='_compute_partnumber',
        inverse='_set_partnumber', store=True)

我把函数写成内参代码

@api.depends('product_variant_ids', 'product_variant_ids.partnumber')
def _compute_partnumber(self):
    unique_variants = self.filtered(lambda template: len(template.product_variant_ids) == 1)
    for template in unique_variants:
        template.partnumber = template.product_variant_ids.partnumber
    for template in (self - unique_variants):
        template.partnumber = ''

@api.one
def _set_partnumber(self):
    if len(self.product_variant_ids) == 1:
        self.product_variant_ids.partnumber = self.partnumber

我在产品中成功添加了部件号 form.I 使用上面的方法获取名称(在产品描述中获取部件号)

我的问题是无法在创建方法中保存部件号。 该字段仅保存在编辑模式

正如 "dccdany" 在他的评论中所说,模板的创建顺序有点棘手。你可以看到它in the code。首先将创建模板。不会设置部件号,因为此时不存在变体。 模板创建后,将创建没有零件编号的变体(后一行),因此模板创建后将没有零件编号。

你能做什么?只需覆盖 product.template create(),如:

@api.model
def create(self, vals):
    template = super(ProductTemplate, self).create(vals)
    if 'partnumber' in vals and len(template.product_varient_ids) == 1:
        template.partnumber = vals.get('partnumber')
    return template