Odoo 中使用和不使用 sudo() 的区别

Difference between with and without sudo() in Odoo

有什么区别:

test = self.env['my.example'].sudo().create({'id':1, 'name': 'test'})

test = self.env['my.example'].create({'id':1, 'name': 'test'})

所有示例都有效,但是使用 sudo() 有什么优势?

Odoo 8–12

在调用 create() 之前调用 sudo()(不带参数)将 return 具有已更新环境并设置了管理员(超级用户)用户 ID 的记录集。这意味着对您的记录集的进一步方法调用将使用管理员用户,因此绕过访问 rights/record 规则检查 [source]。 sudo() 还带有一个可选参数 user,它是将在环境中使用的用户 (res.users) 的 ID(SUPERUSER_ID 是默认值)。

不使用 sudo() 时,如果调用您的方法的用户没有 my.example 模型的 create 权限,则调用 create 将失败并显示 AccessError.

因为访问 rights/record 规则不适用于超级用户,所以应谨慎使用 sudo()。此外,它可能会产生一些不良影响,例如。在多公司环境中混合来自不同公司的记录,由于缓存失效导致的额外重新获取(请参阅 Model Reference 中的 环境交换 部分)。

Odoo 13+

从Odoo 13开始,调用sudo(flag) will return the recordset in a environment with superuser mode enabled or disabled, depending if flag is True or False, respectively. The superuser mode does not change the current user, and simply bypasses access rights checks. Use with_user(user)实际切换用户。

您可以在 odoo -> models.py -> def sudo() 查看 Odoo 代码中 sudo 的评论。

Returns 此记录集的新版本附加到提供的 用户。

    By default this returns a ``SUPERUSER`` recordset, where access
    control and record rules are bypassed.

    It is same as:

    from odoo import api, SUPERUSER_ID

    env = api.Environment(cr, SUPERUSER_ID, {})

    In this example we pass SUPERUSER_ID in place of uid at the time of creating a Enviroment.

    If you are not use Sudo() then the current user need permission to 
    create a given object.


    .. note::

        Using ``sudo`` could cause data access to cross the
        boundaries of record rules, possibly mixing records that
        are meant to be isolated (e.g. records from different
        companies in multi-company environments).

        It may lead to un-intuitive results in methods which select one
        record among many - for example getting the default company, or
        selecting a Bill of Materials.

    .. note::

        Because the record rules and access control will have to be
        re-evaluated, the new recordset will not benefit from the current
        environment's data cache, so later data access may incur extra
        delays while re-fetching from the database.
        The returned recordset has the same prefetch object as ``self``.