Menu

The environment in Odoo is an object that stores various contextual data used by the ORM. This data includes:

  • the current user (user)
  • the cursor (cr)
  • the superuser flag (su)
  • the context (context)

1.Predefined functions

env.ref(xml_id, raise_if_not_found=True)

It will return the record corresponding to the xml_id

Example

>>> self.env.ref('base.user_admin')
res.users(2,)
                        

env.user

It will return the current user of the environment. The returned output will be a record from res.users

env.lang

It will return the language code for the current environment. It will be of str type.

env.company

It will return the current company and will be a record of model res.company.

env.companies

Return a record set of the enabled companies by the user.

2.Altering the Environment

with_context([context][, **overrides]) → records

This method creates a new version of this recordset with an additional context.

# current context is  {'key1': True}
result1 = records.with_context({}, key2=True)
# result1._context is {'key2': True}
result2 = records.with_context(key2=True)
# result2._context is {'key1': True, 'key2': True}
                        

with_user(user)

Return a new version of this recordset in non-superuser mode connected to the specified, unless the user is the superuser

with_company(company)

Return a new version of this recordset with a modified context, such that:

result.env.company = company
result.env.companies = self.env.companies | company
                        

with_env(env)

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

3.SQL Execution

The cursor for the current database transaction is represented by the cr attribute on environments.

It allows you to run SQL directly instead of using the ORM, which is useful for queries that are difficult to define using the ORM (e.g., complex joins) or for performance reasons:

self.env.cr.execute("some_sql", params)
                        
Share this post
Hooks for Odoo modules