Obtaining an empty recordset for a different model

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.

Getting ready

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.

How to do it…

To get a recordset for library.members in a method of library.book, you need to take the following steps:

  1. In the LibraryBook class, write a method called get_all_library_members:
    class LibraryBook(models.Model):
        # ...
        @api.model
        def get_all_library_members(self):
            # ...
  2. In the body of the method, use the following code:
            library_member_model = self.env['library.member']
            return library_member_model.search([])

How it works…

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.

See also

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.167.176