Model.with_env() in Odoo

Temporarily Change the Model's Environment

Model.with_env()

The with_env() method temporarily changes the environment of the current model to the new environment.

This can be useful for testing code in different contexts or accessing data that is not normally accessible in the current environment.

Return a new version of this recordset attached to the provided environment

How to Use

To use with_env(), create a new environment object and pass it as an argument:

env_object = self.env(user=self.browse_ref('base.public_user'))
self = self.with_env(env_object)
# Alternative
env_object_ = api.Environment(cr, self._session.uid, self.session.context)
self = self.with_env(env_object)

Why is it Important?

  • Testing code in different environments (e.g., production vs. development)

  • Changing the database cursor (Cr), context, user, and language for specific tasks

  • Modifying the entire environment for the model

Do We Have Other Options?

๐˜๐ž๐ฌ ๐ฌ๐ฎ๐ซ๐ž , and we discussed in previous Posts you can check from here

ย