1

我正在使用 Odoo 10,我正在尝试修改车队模块,如下图所示

车队模块

我们需要字段“Conductor”(驾驶员)是唯一的,我的意思是,一辆车只能分配一个驾驶员,而驾驶员不能分配超过一辆车。

我使用了这段代码:

@api.constrains('driver_id')
    def _check_driver(self):
        for record in self:
            if record.driver_id in self:
                raise ValidationError("Driver already has a vehicle assigned")

但该代码不起作用。我该如何解决?

4

2 回答 2

1

您可以在字段定义中应用域过滤器,如下所示

#definition on the fleet.vehicle model
driver_id = fields.Many2one('res.partner', index=True, required=True,
    ondelete='cascade', domain=[('vehicle_id', '=', False)])

#definition on the res.partner model
vehicle_id = fields.One2many('fleet.vehicle', 'driver_id')

或如下:

@api.constrains('driver_id')
def _check_driver(self):
    FleetVehicle = self.env['fleet.vehicle']
    for record in self:
        if record.driver_id in self:
            vehicle_count = FleetVehicle.search_count(['driver_id', '=', record.driver_id])
            if vehicle_count > 0:
                raise ValidationError("Driver already has a vehicle assigned")
于 2018-02-15T23:32:35.303 回答
0
_sql_constraints = [
        ('driver_unique', 'UNIQUE(driver_id, )',
         'The Driver has been already assigned to a vehicle !'),
    ]
于 2018-02-21T10:29:25.103 回答