python 多对一字段的动态域,无变化

dsekswqp  于 2023-03-28  发布在  Python
关注(0)|答案(2)|浏览(124)

我需要为many2one字段添加动态域基于另一个(布尔)字段没有onchange函数..我下面的代码不工作..

is_bus_registered = fields.Boolean(
    string='Bus Registered',
    required=False)

def _domain_att_policy(self):
    if self.is_bus_registered:
        policies = self.env['hr.attendance.policy'].search([('is_bus_registered', '=', True)]).ids
        return [('id', 'in', policies)]
    else:
        policies = self.env['hr.attendance.policy'].search([('is_bus_registered', '=', False)]).ids
        return [('id', 'in', policies)]

att_policy_id = fields.Many2one('hr.attendance.policy', string='Attendance Policy', domain=_domain_att_policy)
iqjalb3h

iqjalb3h1#

如果表单视图中有字段is_bus_registered,下面的字段定义就足够了:

att_policy_id = fields.Many2one(
    comodel_name='hr.attendance.policy',
    string='Attendance Policy',
    domain='[("is_bus_registered", "=", is_bus_registered)]')

请记住以下几点:如果用户使用is_bus_registered==False设置策略,然后将is_bus_registered更改为True,则在没有onchange事件的情况下策略不会更改。这可能会导致错误的策略。因此使用或定义onchange事件可能并不那么糟糕。

yhuiod9q

yhuiod9q2#

我用onchange添加了另一个字段many2many

@api.onchange('is_bus_registered')
def _onchange_is_bus_registered(self):
    for rec in self:
        if rec.is_bus_registered:
            rec.att_policy_id = False
            policy_ids = []
            policies = self.env['hr.attendance.policy'].search(
                [('is_bus_registered', '=', True)])
            for policy in policies:
                policy_ids.append(policy.id)
            rec.att_policy_ids = policy_ids
        else:
            rec.att_policy_id = False
            policy_ids = []
            policies = self.env['hr.attendance.policy'].search(
                [('is_bus_registered', '=', False)])
            for policy in policies:
                policy_ids.append(policy.id)
            rec.att_policy_ids = policy_ids

att_policy_ids = fields.Many2many('hr.attendance.policy', string='Attendance Policy')

然后在表单视图中添加,但不可见,并将其放在many2one字段的静态域中..它工作正常

<field name="att_policy_ids" invisible="1"/>
<field name="att_policy_id" required="1" domain="[('id','in',att_policy_ids)]"/>

相关问题