使用xml_id获取记录实例 或 模型+id

Posted 每天投食

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用xml_id获取记录实例 或 模型+id相关的知识,希望对你有一定的参考价值。

此章是一个小的知识点,希望对你有用。


在odoo框架中,外部ID是非常有用的,通常用于我们导入(更新)数据,初始化数据等。

外部ID(也称为xml_id)是数据记录的标识符,Odoo使用基本模ir.model.data将标识符与相应的实际数据库ID映射。


我们在源码中可以看到官方对它的描述:

class IrModelData(models.Model): """Holds external identifier keys for records in the database. This has two main uses:
* allows easy data integration with third-party systems, making import/export/sync of data possible, as records can be uniquely identified across multiple systems * allows tracking the origin of data installed by Odoo modules themselves, thus making it possible to later update them seamlessly. """


有兴趣的可以在源码中,看到此模型提供的便捷方法,下面我将介绍几个常用的方法:


  • 方法一:传入模块名称与xml_id返回记录实例,下面是源码与使用案例截图:

@api.modeldef get_object(self, module, xml_id): """ Returns a browsable record for the given module name and xml_id. If not found, raise a ValueError or return None, depending on the value of `raise_exception`. """ return self.xmlid_to_object("%s.%s" % (module, xml_id), raise_if_not_found=True)

  • 方法二:传入模块名称与xml_id返回模型名称与id,下面是源码与使用案例截图:

@api.modeldef get_object_reference(self, module, xml_id): """Returns (model, res_id) corresponding to a given module and xml_id (cached) or raise ValueError if not found""" return self.xmlid_lookup("%s.%s" % (module, xml_id))[1:3]


下面我就不一一截图了

  • 方法三:传入xml_id返回id

@api.modeldef xmlid_to_res_id(self, xmlid, raise_if_not_found=False): """ Returns res_id """ return self.xmlid_to_res_model_res_id(xmlid, raise_if_not_found)[1]
  • 方法四:传入xml_id切换该记录noupdate标志(noupdate为Boolean类型的字段,当该字段为True时,升级模块并不会导致初始化数据被重置)

@api.modeldef toggle_noupdate(self, model, res_id): """ Toggle the noupdate flag on the external id of the record """ record = self.env[model].browse(res_id) if record.check_access_rights('write'): for xid in self.search([('model', '=', model), ('res_id', '=', res_id)]): xid.noupdate = not xid.noupdate


以上是关于使用xml_id获取记录实例 或 模型+id的主要内容,如果未能解决你的问题,请参考以下文章

php ВыводXML_IDсвойства

解决报错:在pycharm中使用os模块获取当前进程id,出现错误:AttributeError: module ‘os‘ has no attribute ‘getgid‘(图文并茂!!!)(代码片

使用 rank() 时未能将窗口调用分解为组

Laravel:使用模型查询构建器获取重复记录的结果

为啥我不能从 VBA 中的多实例表单中获取当前记录 ID

如何在保存实例之前获取 django 模型实例的 pk