简体   繁体   English

从 python function odoo 14 创建外部标识符

[英]Create external identifier from python function odoo 14

I want to create external identifiers for model 'res.product' from another model.. I tried the following code, but not generated exact as when we export data我想从另一个 model 为 model 'res.product' 创建外部标识符。我尝试了以下代码,但没有像我们导出数据时那样生成

collections=self.env['res.product'].search([('categ','=','nuts')])
        if collections:


            for col in collections:
               

                postfix = 0
                name = '%s_%s' % (col._table, col.id)
                print("name",name)
                ir_model_data = self.sudo().env['ir.model.data']
                while ir_model_data.search([('module', '=', '__export__'), ('name', '=', name)]):
                    postfix += 1
                    name = '%s_%s_%s' % (col._table, 21, postfix)
                ir_model_data.create({
                    'model': 'res.product',
                    'res_id': col.id,
                    'module': '__export__',
                    'name': name,
                })


If ir.model.data already exists for that one record, you should update it instead of creating a duplicate.如果该记录的ir.model.data已经存在,您应该更新它而不是创建副本。

for col in self.env['res.product'].search([('categ','=','nuts')]):
  ir_model_data = self.env['ir.model.data'].sudo().search([
    ('model', '=', 'res.product'),
    ('res_id', '=', col.id)
  ])

  if ir_model_data:
    ir_model_data.write({"name": "UNIVOQUE_EXTERNAL_ID"})
  else:
    self.env['ir.model.data'].create({
      "model": "res.product",
      "res_id": res.id,
      "module": "__import__",
      "name": "UNIVOQUE_EXTERNAL_ID"
    })

You should consider adding this logic in create function of res.product model. This way it won't be massive.您应该考虑在res.product model 的create function 中添加此逻辑。这样它就不会很大。

Otherwise, if it is a one time operation, consider directly executing an SQL query in your database.否则,如果是一次性操作,请考虑直接在您的数据库中执行 SQL 查询。

UPDATE ir_model_data SET name = 'UNIVOQUE_NAME' WHERE model = 'res.product' AND id = 123;

Note that module attribute in ir_model_data indicates if record has been imported, exported or initiated via module data .请注意, ir_model_data中的module属性指示记录是否已通过模块data导入、导出或启动。 Consider using your module name as module or, depending on your needs, __import__ or __export__ tags.考虑使用您的模块名称作为module ,或者根据您的需要, __import____export__标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM