Skip to Content
Menu
This question has been flagged

I using Odoo14,


I create a new custom model that inherit email field from res.partner, and want to make email for each of my users which is students be unique.


Here is my snipet of code:


class AqurStudent(models.Model):
_name = "aqur.student"
_description = "AQUR Student"
_inherit = ['mail.thread', 'mail.activity.mixin']
_inherits = {"res.partner": "partner_id"}
partner_id = fields.Many2one('res.partner', 'Partner', required=True, ondelete="cascade")

@api.constrains('email')
def _check_email(self):
for record in self:
if record.email == record.email:
raise ValidationError('The email already registered, please use another email!')

res_partner = self.env['res.partner'].search_count([('email', '=', self.email)])
if len(res_partner) > 1:
raise ValidationError('The email already registered, please use another email!')

_sql_constraints = [
('email_key', 'UNIQUE (email)', 'The email already registered, please use another email!')
]
The code above seems doesn't have any effect, I still can duplicate my students email and doesn't raise  a ValidationError.


So,  whats  wrong  with  my  code  above?

Please,  any  help,  source  or  tutorial  how  to  face  this  will  be  very  thanks,


Thanks,

Tri  Nanda 

Avatar
Discard
Author Best Answer

Finanly I solved this isue using this following code:

class Partner(models.Model):
_inherit = "res.partner"

@api.constrains('email')
def _check_email(self):
count_email = self.search_count([('email', '=', self.email)])
if count_email > 1 and self.email is not False:
raise ValidationError('The email already registered, please use another email!')

I don't find the way yet, how to use constrains on inherit model, so then I create the constrains code on the model that store the email field directly.


Thanks,

Tri Nanda


Avatar
Discard
Best Answer

You can use the code as below,

@api.model
def create(self, vals):
    previous_email = self.env['aqur.student'].search([('email','=',vals['email'])])
    if len(previous_email) >= 1:         raise ValidationError(_("This Email is Already Taken"))


Try to follow the above techniques, i hope this will solve your issue.



Avatar
Discard
Related Posts Replies Views Activity
1
Oct 22
1576
2
Jan 24
3597
0
Jul 23
1022
1
Aug 22
2310
0
Feb 22
2265