What is different between:
test = self.env['my.example'].sudo().create({'id':1, 'name': 'test'})
test = self.env['my.example'].create({'id':1, 'name': 'test'})
All example work, but what is the advantages when using sudo()
?
Calling sudo()
(with no parameters) before calling create()
will return the recordset with an updated environment with the admin (superuser) user ID set. This means that further method calls on your recordset will use the admin user and as a result bypass access rights/record rules checks [source]. sudo()
also takes an optional parameter user
which is the ID of the user (res.users
) which will be used in the environment (SUPERUSER_ID
is the default).
When not using sudo()
, if the user who calls your method does not have create
permissions on my.example
model, then calling create
will fail with an AccessError
.
Because access rights/record rules are not applied for the superuser, sudo()
should be used with caution. Also, it can have some undesired effects, eg. mixing records from different companies in multi-company environments, additional refetching due to cache invalidation (see section Environment swapping in Model Reference).
Starting with Odoo 13, calling 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)
to actually switch users.