如何在 odoo 10 中创建 Many2One 约束

How to make a Many2One constraint in odoo 10

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

我们需要字段 "Conductor" (Driver) 是唯一的,我的意思是,一辆车只能分配一个 driver 而 driver 不能分配了不止一辆车辆。

我使用了这个代码:

@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")

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

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

#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")
_sql_constraints = [
        ('driver_unique', 'UNIQUE(driver_id, )',
         'The Driver has been already assigned to a vehicle !'),
    ]