odoo 动态设置selection字段
selection字段一般为下拉选择列表。
我们经常会将selection字段编写成由"若干对键值对的元组组成的列表"。 如下:
state = fields.Selection( selection= [(key, value), (key1, value1), ...], string=u'状态')
这种selection的选项内容基本是固定,但是针对一些特殊要求,需要动态创建选项内容的设置。
state = fields.Selection( selection= '_selection_filter', string=u'状态')
@api.model
def _selection_filter(self):
res_filter = [(key1, value1)]
# 可以根据不同的身份或者群组对res_filter进行处理。
if case1:
res_filter += [(key2, value2)]
else:
res_filter += [(key3, value3)]
if case2:
res_filter.remove(0)
return res_filter
- 以上这种方式定义Selection需更新应用才能更新字段。
- 也可从从别的模型查询数据进行设置,如下:
@api.model
def _get_bank(self):
bank_obj = self.env['hr.bank.info']
banks = bank_obj.search([('allow', '=', True)])
# 查询银行信息表,将银行编码、银行名称设置为selection需要的格式
selection = [(bank.bank_code, bank.bank_name) for bank in banks]
return selection
bank_name = fields.Selection(selection='_get_bank',string=u'开户银行')