Odoo的只读字段在onchange中被改变时,如何保存到数据库

Readonly field in onchange method

If you change the value of a readonly field in onchange method, on save it will not be stored in the database. In order to do that you would need to override create/write methods where you would need to update the values dictionary with this value before creation.

For example, you would need to update the readonly field “invoice_method” the depends on the “partner_id” field. If you change its value in the onchange_partner_id method

@api.onchange('partner_id')
def onchange_partner_id(self):
    res = super(MrpRepair, self).onchange_partner_id()
    self.invoice_method = self.partner_id.prepaid and 'b4repair' or 'after_repair'
    return res

the new value will not be stored in the database on save. Instead, you would need to extend the create method and to update the “vals” dictionary before creation

@api.model
def create(self, vals):
    if vals.get('partner_id'):
        vals.update({'invoice_method': self.env['res.partner'].browse(
                    vals.get('partner_id')).prepaid and 'b4repair' or 'after_repair'})
    return super(MrpRepair, self).create(vals)

查到资料中给出的解决方式是重写create / write 方法,存到数据库。我试了一下,貌似没有效果,可能是我哪里写错了。就去搜了一下odoo的源码,看到在是视图中,有很多readonly 的字段还有一个属性 叫 force_save,就象下面这样:

从字面上理解这个属性 ,强制保存,感觉有戏, 而且果然有戏。

 

你可能感兴趣的:(Odoo的只读字段在onchange中被改变时,如何保存到数据库)