odoo开发笔记--模型字段compute用法
compute属性,实现的主要功能是,前端界面选择某个字段的时候,指定与该字段关联的其他字段可以关联,并联动的显示。
可以和inverse属性同时使用,不加inverse属性的话,前端界面的显示效果只是只读样式,不能编辑修改;而加上inverse属性时候,相应的关联字段可以修改,
但是,修改后,实际上修改的是原表;即会将原表的数据级联更改。
class HelloJesson(models.Model): _name = 'test.cus_goods_list' # rec_name = 'goods_name' _inherit = ['mail.thread', 'ir.needaction_mixin'] _description = 'Test Goods List' goods_name = fields.Char(compute='_generate_about_name', string="goods name", inverse='_write_stage_fold') cus_goods_tariff_id = fields.Many2one(comodel_name="other_yourself_model.cus_goods_tariff", string="cus goods Code TS", required=False, ) @api.onchange('cus_goods_tariff_id') def _generate_about_name(self): """根据当前cus_goods_tariff_id的变化 动态关联显示goods_name""" for goods_list in self: if goods_list.cus_goods_tariff_id: goods_list.goods_name = goods_list.cus_goods_tariff_id.NameCN def _write_stage_fold(self): """ inverse='_write_stage_fold' 增加可编辑功能 但是inverse会将原来表中的数据级联修改""" for goods_list in self: if goods_list.cus_goods_tariff_id: goods_list.cus_goods_tariff_id.NameCN = self.goods_name
实现compute字段 前端可以编辑修改的方法有两种:
(1)我们可以在模型定义中,再单独添加一个字段g_name,然后该字段根据compute生成的那个字段good_name的值进行取值并赋值给g_name;
class HelloJesson(models.Model): _name = 'test.cus_goods_list' rec_name = 'g_name' _inherit = ['mail.thread', 'ir.needaction_mixin'] _description = 'Test Goods List' g_name = fields.Char(string="goods name") # 商品名称 goods_name = fields.Char(compute='_generate_about_name', string="goods name", store=True) # 商品名称 cus_goods_tariff_id = fields.Many2one(comodel_name="other_yourself_model.cus_goods_tariff", string="cus goods Code TS", required=False, ) @api.onchange('goods_name') def change_name(self): """由于compute字段前端无法编辑,定义新方法,ID改变生成商品名改变goods_name,再由goods_name的变化,触发赋值给g_name""" for goods_list in self: if goods_list.goods_name: # goods_list.update({'name': goods_list.goods_name}) goods_list.g_name = goods_list.goods_name @api.depends('cus_goods_tariff_id') def _generate_about_name(self): """根据cus_goods_tariff_id编码的变化 改变goods_name""" for goods_list in self: if goods_list.cus_goods_tariff_id: goods_list.goods_name = goods_list.cus_goods_tariff_id.NameCN
(2)方式二,可以直接将compute属性去掉,装饰器使用@api.onchange,可以直接实现前端相关字段动态生成,并且可以编辑的效果。