本文實際上是對 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 時,才執行如下代碼。