Openerp, how to make a unique record
<p>I am currently working with <code>hr_holidays</code> (aka <code>Leave Management</code>) Module and I need to add leave allocation as a unique record for given type of leave.</p>

<p>I have added one extra condition in the <code>create()</code> function and that result in  not allowing any making leave request to be made. </p>

<p>Following is my <code>create()</code> function:   </p>

<pre><code> def create(self, cr, uid, values, context=None):

    #-------what I have added starting from here------

    hol_stat=values['holiday_status_id']
    emp_id=values['employee_id']
    n_allo=values['test_allocation']

    ids=self.pool.get('hr.holidays').search(cr, uid, [('holiday_status_id','=', hol_stat),('employee_id','=', emp_id),('type','=','add')], context=context)
        if ids:
            raise osv.except_osv(_('Warning!'),_('Already allocated leaves .'))
    # ------end from here-----


        """ Override to avoid automatic logging of creation """
        if context is None:
            context = {}
        context = dict(context, mail_create_nolog=True)

        if ('date_from' in values and 'date_to' in values):
            define_holidays = self.pool.get('company.holidays').search(cr, uid, ['|',('date', '=', values['date_from']),('date', '=', values['date_to'])])

            if define_holidays:
                raise osv.except_osv(_('Warning!'),_('You need not to apply leaves one Company holidays.'))
            else: 
                return super(hr_holidays, self).create(cr, uid, values, context=context)
        else:#mani
            return super(hr_holidays, self).create(cr, uid, values, context=context)
</code></pre>

<p><strong>Question</strong></p>

<p>How can I alter my <code>create()</code> function to achieve the unique record requirement?</p>

<p>Instead of doing a search anytime you want to create a new record, enforce a <code>UniqueConstraint</code> on the database, that wouldn't allow duplicate records to be created, with this</p>

<pre><code>_sql_constraints = [
        ('unique_hol_empid_type', 'unique(holiday_status_id, employee_id, type)', 'Error: Already allocated leaves'),
    ]
</code></pre>

<p>the unique constraint is a combination of the three columns you want, and <code>unique_hol_empid_type</code> is the name we gave to the constraint (at the database layer) and the error will be raised anytime a record violates that constraint.</p>

python python-2.7 openerp