之间有什么不同:
test = self.env['my.example'].sudo().create({'id':1, 'name': 'test'})
test = self.env['my.example'].create({'id':1, 'name': 'test'})
所有示例都有效,但使用sudo()
时有什么优势?
答案 0 :(得分:9)
在调用sudo()
之前调用create()
(没有参数)将返回记录集,其中包含设置了admin(超级用户)用户ID的更新环境。这意味着对记录集的进一步方法调用将使用admin用户,因此绕过访问权限/记录规则检查[source]。 sudo()
还会使用可选参数user
,该参数是将在环境中使用的用户ID(res.users
)(默认为SUPERUSER_ID
)。
如果不使用sudo()
,如果调用您的方法的用户对create
模型没有my.example
权限,则调用create
将失败并显示{{1} }}
由于访问权限/记录规则未应用于超级用户,因此应谨慎使用AccessError
。此外,它可能会产生一些不良影响,例如。在多公司环境中混合来自不同公司的记录,由于缓存失效而导致额外的重新获取(请参阅Model Reference中的环境交换部分)。
答案 1 :(得分:1)
您可以在sudo
的Odoo代码中查看odoo -> models.py -> def sudo()
上的评论。
答案 2 :(得分:1)
返回附加到提供的此记录集的新版本 用户。
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``.