如果字段为空 odoo 12,如何引发验证错误?

How to Raise a validation error if a field is empty odoo 12?

我尝试做的是,如果 specialist_name 为空,我必须引发验证错误。但它不起作用。我究竟做错了什么?我的 python 代码如下:

specialist_name = fields.Many2one(
    'res.partner',domain=[('is_specialist','=',True)],string="Specialist")

@api.constrains('specialist_name')
def _onchange_value(self):
    if self.specialist_name == False:
        raise ValidationError(_('Only The Specialist Has The Provision To Create'))

specialist_name是一个Many2one字段,该字段的值为大小为0(无记录)或1(单条记录)的记录集。

self.specialist_name == False 表达式将始终计算为 False 并且永远不会执行 if 语句的主体。

空记录在诸如 if 或 while 语句的布尔上下文中被评估为 False,尝试使用:

if not self.specialist_name:

编辑:

@constrains will be triggered only if the declared fields in the decorated method are included in the create or write call. It implies that fields not present in a view will not trigger a call during record creation. An override of create is necessary to make sure a constraint will always be triggered (e.g. to test the absence of value).

如果您覆盖 createwrite 方法,您会发现 specialist_name 键不存在于值中,如果您将专家名称添加到值中,约束将起作用.

当我们设置只读字段时,我们阻止用户修改它并在后台处理它的值。我们不需要警告用户,因为无法从 UI.

更改字段的值

为什么不使用更简单的解决方案并将该字段设为必填?

大体上有两个 positions/areas 可以做到。

  1. 关于视图,这将使您在实施过程中具有一定的灵活性(也许在某些情况下您不想要求它)
<field name="my_field" required="1" />
  1. 关于字段声明
my_field = fields.Many2one(comodel_name="my.comodel", required=True)