Navi
Navi

Reputation: 1052

How to prevent field value repetition on already assigned date in Odoo?

I am working with Odoo 10.

I have a one2many field with two columns in the hr.employee model. If the field "Bonus" (many2one field) is assigned to a particular date, it should not be saved or repeated once again on the same date.

How to achieve this?

Current screen

Upvotes: 3

Views: 2106

Answers (3)

Medo_ban
Medo_ban

Reputation: 1

you can use constraints and the search_count() method to check if there is a record. like below

@api.constraints('date')
def validate_date(self):
    result = self.search_count([your_domain])
    if result:
        raise ValidationError(_('Your Text'))

Upvotes: 0

Santhosh
Santhosh

Reputation: 219

Use constrains to stop creating another record with the same name, so duplication of records doesnot occur.

Upvotes: 0

ChesuCR
ChesuCR

Reputation: 9620

Take a look at this below code, this is one possible solution, not the best.

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
    )

And then you need to add the constrains:

Solution 1

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

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

Note: If you have date already in your database make sure that the constrains can be added with this data, because if not the constraint cannot be added to the database. This happens with the _sql_constraints at least

Upvotes: 2

Related Questions