如何防止在Odoo中已分配日期的字段值重复?

我正在使用Odoo 10.

我在hr.employee模型中有一个带有两列的one2many字段.如果将“奖励”字段(many2one字段)分配给特定日期,则不应保存该字段或在同一日期再次重复该字段.

如何实现呢?

如何防止在Odoo中已分配日期的字段值重复?

解决方法:

看看下面的代码,这是一种可能的解决方案,而不是最好的解决方案.

from odoo import models, fields, api
from odoo.exceptions import ValidationError

class HrEmployee(models.Model):
    _inherit = 'hr.employee'

    prod_details_ids = fields.One2many(
        string=u'Product details',
        comodel_name='prod.details',
        inverse_name='employee_id',
    )

class ProdDetails(models.Model):
    _name = 'prod.details'

    employee_id = fields.Many2one(
        string=u'Employee',
        comodel_name='hr.employee',
    )

    date = fields.Date(
        string=u'Date',
        default=fields.Date.context_today,
    )

    bonus_id = fields.Many2one(
        string=u'Bonus',
        comodel_name='res.partner',  # just an example
    )

然后,您需要添加约束:

解决方案1

    _sql_constraints = [
        ('bonus_unique', 'unique(employee_id, date, bonus_id)',
         _('Date + Bonus cannot be repeated in one employee!')),
    ]

解决方案2

    @api.one
    @api.constrains('date', 'bonus_id')
    def _check_unique_date(self):

        # you have more freedom here if you want to check more things

        rest = self.employee_id.prod_details_ids - self
        for record in rest:
            if record.date == self.date and record.bonus_id.id == self.bonus_id.id:
                    raise ValidationError("Date + Bonus already exists and violates unique field constraint")

注意:如果数据库中已经有日期,请确保可以将约束与该数据一起添加,因为如果没有约束,则不能将约束添加到数据库中.至少_sql_constraints会发生这种情况

上一篇:独家分享:补充免费开源ERP Odoo的安全审计机制的最后一环功能


下一篇:odoo里的rpc用法