Difference between  sudo() and with_env() in Odoo


✅ sudo()

Executes operations as superuser

Ignores access rights and record rules


✅ with_env()

Changes the execution environment

Can switch user, context, or company

Does not automatically bypass security


✅ sudo() Example

order = self.env[‘sale.order’].sudo().browse(order_id)

order.write({‘note’: ‘Updated by system’})

✅ Useful for cron jobs

❌ Dangerous if used incorrectly

✅ ​with_env() Example

new_env = self.env(user=self.env.ref(‘base.user_admin’).id)

order = self.env[‘sale.order’].with_env(new_env)

order.write({‘note’: ‘Updated as Admin’})

✔️ Controlled environment

✔️ Useful in multi-user logic

🛡  Key Difference

Feature                              sudo()          with_env()

Bypass access rules                       ✅                         ❌

Change user                                    ❌                         ✅

Safer                                                 ❌                         ✅