When writing Odoo code, the methods of the current model are available via self
. If you need to work on a different model, it is not possible to directly instantiate the class of that model—you need to get a recordset for that model to start working.
This recipe shows how to get an empty recordset for any model registered in Odoo inside a model method.
This recipe will reuse the setup of the library example in the addon module my_module
.
We will write a small method in the library.book
model searching for all library.members
. To do this, we need to get an empty recordset for library.members
.
To get a recordset for library.members
in a method of library.book
, you need to take the following steps:
LibraryBook
class, write a method called get_all_library_members
:class LibraryBook(models.Model): # ... @api.model def get_all_library_members(self): # ...
library_member_model = self.env['library.member'] return library_member_model.search([])
At start up, Odoo loads all the modules and combines the various classes deriving from Model
and defining or extending a given model. These classes are stored in the Odoo registry indexed by name. The environment in self.env
provides a shortcut access to the registry by emulating a Python dictionary; if you know the name of the model you're looking for, self.env[model_name]
will get you an empty recordset for that model. Moreover, the recordset will share the environment of self
.
The call to search()
is explained in the Searching for records recipe later.
The
Changing the user performing an action and Calling a method with a modified enviroment recipes in Chapter 6, Advanced Server Side Development Techniques, deal with modifying self.env
at runtime.
3.145.167.176