3

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

ChesuCR
  • 9,352
  • 5
  • 51
  • 114
Navi
  • 1,000
  • 1
  • 14
  • 44

3 Answers3

2

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

ChesuCR
  • 9,352
  • 5
  • 51
  • 114
  • It does'nt satisfy my need @ChesuCR – Navi Jan 02 '18 at 20:34
  • Maybe you don't need exactly the code what I wrote, but you need that tool to build the constraint. Could you please write your code to let me be more specific @naveen? – ChesuCR Jan 08 '18 at 00:21
  • @Naveen I have updated my answer with two possible solutions, check if they are useful for you – ChesuCR Jan 21 '18 at 22:51
0

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

Santhosh
  • 209
  • 2
  • 16
0

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'))
Medo_ban
  • 1
  • 3