odoo 动态创建字段

有这样的一个需求,在test表里,有个字段直接关联模型,但是在test表里,选择的一个模型就要创建一个字段来对应此模型,因为在odoo 中,模型数量太多,无法直接创建字段来使用,
故使用动态的创建字段。
类似:
选择 res.users生成字段 x_res_users_id
选择 account.move 生成字段 x_account_move_id
类似生成这种字段,如果存在则不创建

    def dynamic_field(self, dimension_ids):
        """ 动态创建字段
        self._name: 传过来的模型(要在那个模型里面创建字段)
        fields_name :生成字段,类似 x_res_users_id
       """
        for rec in dimension_ids:
            model = self.env['ir.model']._get(self._name)
            fields_name = 'x_%s_id' % (rec.dimension_id.model_id.model.replace('.', '_'))
            if fields_name not in self:
                new_field = self.env['ir.model.fields'].create({
                    'model_id': model.id,  
                    'name': fields_name, 
                    'field_description': rec.dimension_id.model_id.name,   
                    'ttype': 'many2one',
                    'relation': rec.dimension_id.model_id.model,
                })

#model_id 在此模型创建字段
#name 字段名称
#field_description 字段描述
#ttype 字段类型
#relation ttype 关联的模型,

猜你喜欢

转载自blog.csdn.net/weixin_42464956/article/details/108213874