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

时间:2017-06-05 06:26:38

标签: python openerp edit

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

这是我的代码:

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

创建产品时,代码运行正常。

但是当我编辑产品&删除选定的供应商,它不再起作用。

有人可以向我指出错误吗?谢谢!

编辑:使用约束修复。

2 个答案:

答案 0 :(得分:2)

您可以添加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

答案 1 :(得分:0)

当您创建产品create时,系统会调用该功能,并且一直在编辑write功能。

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

尝试这样的事情

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