因此,当用户尝试输入已存在的同一员工时,它将引发警告或错误消息
我已经完成了这个功能:
class overtime(models.Model):
_name = 'overtime.overtime'
employee_ids = fields.One2many('overtime.overtime_details', 'overtime_id', string="Employee", readonly=True, states={'draft': [('readonly', False)]})
class overtime_details(models.Model):
_name='overtime.overtime_details'
@api.multi
@api.constrains('employee_id')
@api.onchange('employee_id')
def prevent_duplicate(self):
#import pdb;pdb.set_trace()
if self.employee_id:
bruh = self.search([])
for empy in bruh:
if self.employee_id.id == empy.employee_id.id:
raise osv.except_osv(_('Error!'),_('You Cant Enter Same Employee in One Overtime Request!'))
nik = fields.Char('NIK', size=250, required=True)
overtime_id = fields.Many2one('overtime.overtime', string="Overtime", ondelete='cascade')
job_id = fields.Many2one('hr.job', string="Position", readonly=True)
employee_id = fields.Many2one('hr.employee', "Employee", required=True, select=True, copy=False
, domain="[('department_id', '=', parent.department_id)]")
ovrtm = fields.Float(compute=attd_check, string='Overtime Hour(s)')
ttalmtp = fields.Float(compute=overtype_count, string='Total Multiplier')
但它会循环我保存在数据库中的每条记录,所以我需要帮助我应该怎么做,如果我想循环记录我在该会话中输入?我正在研究odoo v8
答案 0 :(得分:1)
这里我通过方法或捕获约束数据库错误给出了可能性:
class overtime(models.Model):
_name = 'overtime.overtime'
employee_ids = fields.One2many('overtime.overtime_details',
'overtime_id', string="Employee",
readonly=True, states={'draft': [('readonly', False)]})
#no need for multi because by default they are multi
@api.onechange('employee_ids')
@api.constrains('employee_ids')
def prevent_dupe(self):
# what you did here is wrong
# it will always give you = 12 because you are
# computing the len of string 'employee_ids' not
# the number of record in the one2many field
# o2m_size = len('employee_ids')
o2m_size = len(self.employee_ids)
employee_count = len(self.employee_ids.mapped('employee_id'))
if o2m_size != employee_count:
raise exceptions.ValidationError(_("Employee already exist!"))
class overtime_details(models.Model):
_name='overtime.overtime_details'
nik = fields.Char('NIK', size=250, required=True)
overtime_id = fields.Many2one('overtime.overtime', string="Overtime", ondelete='cascade')
job_id = fields.Many2one('hr.job', string="Position", readonly=True)
employee_id = fields.Many2one('hr.employee', "Employee", required=True, select=True, copy=False
, domain="[('department_id', '=', parent.department_id)]")
ovrtm = fields.Float(compute=attd_check, string='Overtime Hour(s)')
ttalmtp = fields.Float(compute=overtype_count, string='Total Multiplier')
# if you want to prevent duplicated
# and constrains for that if the method didn't work for you
_sql_constraints = [('unique_imployee_overtime', 'unique(overtime_id,employee_id)',
_(" Deplicated employee in overtime ")), ]
答案 1 :(得分:0)
您可以使用插入的'id'作为参数执行'browse',而不是'search',并检查获得记录集,如果它不为空则引发异常。
这样的事情:
aspx.vb