Wizards and code reuse

In step 2, we could have removed the for loop in the wizard, and by assuming that len(self) will be 1, we can add self.ensure_one() at the beginning of the method, as follows:

def add_book_rents(self):
self.ensure_one()
rentModel = self.env['library.book.rent']
for book in self.book_ids:
rentModel.create({
'borrower_id': self.borrower_id.id,
'book_id': book.id
})

Adding self.ensure_one() at beginning of the method will ensure that the number of records in the self is only one. An error will be raised if there is more than one records in the self.

We recommend using the version in the recipe, though, because this allows us to reuse the wizard from other parts of the code by creating records for the wizard, putting them in a single recordset (refer to the Combining recordsets recipe in Chapter 6, Basic Server-side Development, to see how to do this), and then calling add_book_rents() on the recordset. Here, the code is trivial, and you don't really need to jump through all those hoops to record that some books have been borrowed by different members. However, in an Odoo instance, some operations are much more complex, and it is always nice to have a wizard available that does the right thing. When using these wizards, ensure that you check the source code for any possible use of the active_model/active_id/active_ids keys from the context. If this is the case, you need to pass a custom context (refer to the Calling a method with a modified context recipe).

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

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