Odoo - 在编辑具有空值的某些字段时发出警告

Odoo - Give a warning when editing some field with empty value

如果创建新产品或编辑产品,我想向供应商添加一个条目 table。每个产品都必须有一个供应商。 如果没有选择供应商,系统必须给出警告“您应该至少填写一个供应商详细信息。”

这是我的代码:

class warning_supplier(models.Model):
_inherit = 'product.template'

@api.multi
def write(self, vals):
    res = super(warning_supplier, self).write(vals)
    supplier_id = self.env['res.partner'].search([('name','=','No Supplier')])
    for this in self:
        seller_ids = this.seller_ids
        if len(seller_ids)==0:
            raise Warning('You should fill in the supplier details, at least one.')
    return res

当我创建产品时,代码运行正确。

但是当我编辑产品并删除所选供应商时,它不再起作用了。

谁能给我指出错误?谢谢!


编辑:使用约束修复。

创建产品时调用 create 函数,编辑时总是调用 write 函数。

在创建时你应该检查 vals 参数,如果它不符合要求你应该警告用户更正它,然后编辑实际记录。

尝试这样的事情

# For example boolean
if vals["myBoolean"] == False:
    raise Warning('myBoolean should be true always!')

您可以添加 python 约束,该约束将在给定字段被修改时执行。

class product_template(models.Model):
    _inherit = 'product.template'

    @api.multi
    @api.constrains('seller_ids')
    def onchange_seller(self):
        for record in self :
            if not record.seller_ids :
                raise ValidationError("You should fill in the supplier details, at least one.")
        return

有关约束的更多信息:click here