Odoo 14 CE 中的可选依赖项

Optional Dependencies in Odoo 14 CE

有什么方法可以在 Odoo 14 CE 中创建可选依赖项吗?

我知道manifest文件中有一个dependency属性需要我们指定,是的,我一直在尽力使用它。

然而,有时我只需要在安装模块时编写一些代码,但即使没有安装,其余代码也应该在没有安装该模块的情况下正常运行。

例如,我的自定义模块将在 saleaccount 中添加一个字段,但如果此数据库安装了 purchase,那么它也会在其中添加一个字段。很简单的概念,对吧,但我找不到在单个模块中实现它的方法。

您可以使用 post_init_hook, which is executed right after the module’s installation, to check if the purchase (purchase.order is in registry) module is installed and add the custom field. You can even load an XML file to add the custom field by inheritance using the convert_xml_import 功能转换和导入 XML 个文件。

类似于手动添加字段到相应的模型和视图中。

当您卸载模块时,自定义字段不会被删除,为此,您将需要使用uninstall_hook,由于以下用户错误,您还需要手动删除视图:

User Error
Cannot rename/delete fields that are still present in views
Fields: purchase.order.x_reference
View: purchase.order.form

首先在__manifest__.py文件中设置post_init_hookuninstall_hook函数:

'post_init_hook': '_module_post_init',
'uninstall_hook': '_module_uninstall_hook',

然后在 __init__.py 文件中定义那些函数:

import os
from odoo import fields, api, SUPERUSER_ID, tools, modules
from odoo.tools.misc import file_open


def _module_uninstall_hook(cr, registry):
    if 'purchase.order' in registry:
        env = api.Environment(cr, SUPERUSER_ID, {})
        env.ref('Whosebug_14.purchase_order_form').unlink()
        env['ir.model.fields'].search([('name', '=', 'x_reference')]).unlink()


def _module_post_init(cr, registry):
    if 'purchase.order' in registry:
        env = api.Environment(cr, SUPERUSER_ID, {})
        mp = env['ir.model'].search([('model', '=', 'purchase.order')], limit=1)
        mp.write({'field_id': [(0, 0, {
            'name': 'x_reference',
            'field_description': "Reference",
            'ttype': 'char',
        })]})
        pathname = os.path.join(modules.get_module_path('Whosebug_14'), 'views', 'purchase_order.xml')
        with file_open(pathname, 'rb') as fp:
            tools.convert.convert_xml_import(cr, 'Whosebug_14', fp)

views中定义的purchase_order.xml文件使用视图继承将自定义字段添加到purchase_order_form表单视图:

<?xml version="1.0" encoding="utf-8" ?>
<odoo>
    <data>
        <record id="purchase_order_form" model="ir.ui.view">
            <field name="name">purchase.order.form</field>
            <field name="model">purchase.order</field>
            <field name="inherit_id" ref="purchase.purchase_order_form"/>
            <field name="arch" type="xml">
                <field name="partner_ref" position="after">
                    <field name="x_reference"/>
                </field>
            </field>
        </record>
    </data>
</odoo>