本文实际上是对 default_get 方法的应用,当视图被打开时,就会执行此方法。本文以图书整理到书架举例说明使用方法。
创建向导py文件: wizards/wizards_organize_books.py
class WizardOrganizeBooks(models.TransientModel): _name = "wizard.organize.books" _description = "wizard.organize.books" shelf_id = fields.Many2one('zerone.shelf', index=True, string="书架") book_ids = fields.Many2many('zerone.book', string='图书') def action_organize(self): pass创建向导xml文件: wizards/wizards_organize_books.xml
<field name="shelf_id"/> <field name="book_ids" nolabel="1"> <tree string="Books"> <field name="id"/> <field name="name"/> <field name="email"/> <field name="customer_type"/> </tree> </field> .... <footer> <button name='action_organize' string='整理' class='oe_highlight' type='object'/> <button special="cancel" string="Close" type="object" class="btn btn-secondary oe_inline"/> </footer>重写 default_get 方法
class WizardOrganizeBooks(models.TransientModel): _name = "wizard.organize.books" _description = "wizard.organize.books" shelf_id = fields.Many2one('zerone.shelf', index=True, string="书架") book_ids = fields.Many2many('zerone.book', string='图书') def action_organize(self): pass @api.model def default_get(self, fields): res = super(WizardOrganizeBooks, self).default_get(fields) active_ids = self.env.context.get('active_ids') book_ids = self.env['zerone.book'].browse(active_ids).mapped("id") if self.env.context.get('active_model') == 'zerone.book' and active_ids: res['book_ids'] = [(6, 0, book_ids)] return res应用时,需注意的项,active_ids 就是勾选的记录的id集合,active_model 判断当前模型,如果打开向导时,模型为 zerone.book 时,才执行如下代码。