Reputation: 211
I am currently working with hr_holidays
(aka Leave Management
) Module and I need to add leave allocation as a unique record for given type of leave.
I have added one extra condition in the create()
function and that result in not allowing any making leave request to be made.
Following is my create()
function:
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)
Question
How can I alter my create()
function to achieve the unique record requirement?
Upvotes: 0
Views: 170
Reputation: 9634
Instead of doing a search anytime you want to create a new record, enforce a UniqueConstraint
on the database, that wouldn't allow duplicate records to be created, with this
_sql_constraints = [
('unique_hol_empid_type', 'unique(holiday_status_id, employee_id, type)', 'Error: Already allocated leaves'),
]
the unique constraint is a combination of the three columns you want, and unique_hol_empid_type
is the name we gave to the constraint (at the database layer) and the error will be raised anytime a record violates that constraint.
Upvotes: 1