Sunday, 21 September 2014

Odoo New API: Environment


Share it Please

An environment wraps data for ORM records:

  •  'cr', the current database cursor.
  •  'uid', the current user id.
  •  'context', the current context dictionary.

It also provides access to the registry, a cache for records, and a data structure to manage re-computations.

Encapsulates cr, uid, context:

Accessing the current cursor, user and context:

#recs.env encapsulates cr, uid, context             # shortcut: recs._cr
recs.env.uid           # shortcut: recs._uid
recs.env.context    # shortcut: recs._context

# recs.env also provides helpers
recs.env.user                              # uid as a record
recs.env.ref('base.group_user')  # resolve xml id
recs.env['res.partner']                # access to new-API model

Switching Environments:

1. Switch to new user:

Returns a new version of this recordset attached to the provided user:

self.sudo()               # This will use the SUPERUSER_ID by default
# or

2. Modifying the context:

Returns a new version of this recordset attached to an extended context:

Syntax: with_context([context][, **overrides]) -> records

The extended context is either the provided 'context' in which 'overrides' are merged or the *current* context in which 'overrides' are merged e.g.:
# current context is {'key1': True}
r2 = records.with_context({}, key2=True)
# -> r2._context is {'key2': True}
r2 = records.with_context(key2=True)
# -> r2._context is {'key1': True, 'key2': True}

3. Switch to new Environment:

Returns a new version of this recordset attached to the provided environment:

# rebrowse recs with different parameters
env2 = recs.env(cr2, uid2, context2)
recs2 = recs.with_env(env2)

Dry Run:

Environment context manager provides the helper method to perform the action only in caches:

1. do_in_draft: Context-switch to draft mode, where all field updates are done in cache only.
2. do_in_onchange: Context-switch to 'onchange' draft mode, which is a specialized draft mode used during execution of onchange methods.
Invalidate the Environment Caches:

An Environment maintains multiple caches that are used by the Models/Fields classes.

In some cases, if you want to invalidate the caches, then you can do:


It will clear the cache of all environments.
Comment With:
The Choice is Yours!

1 comment:

  1. Enpersol is an Odoo consultants Company in indore proficient in business process reenginerring and optimization. Enpersol is an Odoo partners Company provide best Odoo services in pune.