Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between with and without sudo() in Odoo

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()?

like image 510
Pointer Avatar asked May 25 '17 07:05

Pointer


1 Answers

Odoo 8–12

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).

Odoo 13+

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.

like image 149
Naglis Avatar answered Sep 27 '22 23:09

Naglis