有這樣的一個(gè)需求躏碳,在test表里哀墓,有個(gè)字段直接關(guān)聯(lián)模型趁餐,但是在test表里,選擇的一個(gè)模型就要?jiǎng)?chuàng)建一個(gè)字段來(lái)對(duì)應(yīng)此模型篮绰,因?yàn)樵趏doo 中后雷,模型數(shù)量太多,無(wú)法直接創(chuàng)建字段來(lái)使用吠各,
故使用動(dòng)態(tài)的創(chuàng)建字段臀突。
類似:
選擇 res.users生成字段 x_res_users_id
選擇 account.move 生成字段 x_account_move_id
類似生成這種字段,如果存在則不創(chuàng)建
def dynamic_field(self, dimension_ids):
""" 動(dòng)態(tài)創(chuàng)建字段
self._name: 傳過(guò)來(lái)的模型(要在那個(gè)模型里面創(chuàng)建字段)
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 在此模型創(chuàng)建字段
#name 字段名稱
#field_description 字段描述
# ttype 字段類型
#relation ttype 關(guān)聯(lián)的模型候学,