我将我的自定义字段添加到res.partner模型中,并且当我创建伙伴(如果选中branch_id时)时,我希望选择3个字段之一。如果未选择某些字段,那么我想引发UserError。
但是现在即使我选择了其中一个字段,它也会引发UserError。
class ResPartner(models.Model):
_inherit = 'res.partner'
branch_id = fields.Many2one('branch.responsibility','Responsibility by branch')
drawer_id = fields.Many2one(
'furniture.parts.type', string='Drawer Type',
domain=[('type', '=', 'drawer')], )
flexible_id = fields.Many2one(
'furniture.parts.type', string='Flexible Type',
domain=[('type', '=', 'flexible')],)
runner_id = fields.Many2one(
'furniture.parts.type', string='Runner Type',
domain=[('type', '=', 'runner')], )
@api.model
def create(self, vals):
if vals.get('branch_id'):
if not vals['drawer_id'] or not vals['flexible_id'] or not vals['runner_id']:
raise UserError('You need to chose values from notebook raport data')
return super(ResPartner, self).create(vals)
更新。
对于写方法,我按照CZoellner建议的创建方法进行了尝试,但始终对fields_to_check_in_vals
取True True True
@api.multi
def write(self, vals):
if vals.get('branch_id') or vals.get('drawer_id') or vals.get('flexible_id') or vals.get('runner_id') or
vals.get('group_1_id') or vals.get('group_2_id')or
vals.get('group_3_id'):
fields_to_check = ['drawer_id', 'flexible_id', 'runner_id', 'group_1_id', 'group_2_id', 'group_3_id']
fields_to_check_in_vals = [f in self for f in fields_to_check]
if not any(fields_to_check_in_vals):
raise UserError('If branch is selected then you need to select one of the fields from data raport')
> return super(ResPartner, self).write(vals)
答案 0 :(得分:1)
您的逻辑说,必须设置所有3个字段。您可以在此处使用any
:
if vals.get('branch_id'):
fields_to_check = ['drawer_id', 'flexible_id', 'runner_id']
fields_to_check_in_vals = [f in vals for f in fields_to_check]
if not any(fields_to_check_in_vals):
raise UserError()
编辑:write
方法比较棘手。通常,它是一种多记录方法,因此应实现针对self的每个循环。然后,您将需要使用getattr
或仅(在Odoo文档中建议)将记录集视为dict。然后可能是更改直接发生在写调用上。因此,您必须检查持久值和新值:
for record in self:
if vals.get('branch_id'):
fields_to_check = ['drawer_id', 'flexible_id', 'runner_id']
fields_to_check_dict = {f:record[f] for f in fields_to_check}
fields_to_check_dict.update({f:f in vals for f in fields_to_check})
if not any(fields_to_check_dict.values()):
raise UserError()
有点复杂。您也可以先致电super
,然后再检查。引发异常将回滚所有更改,因此不会发生任何事情。
res = super(MyModel, self).write(vals)
for record in self:
if vals.get('branch_id'):
fields_to_check = ['drawer_id', 'flexible_id', 'runner_id']
fields_to_check_in_record = [record[f] for f in fields_to_check]
if not any(fields_to_check_in_record):
raise UserError()
return res