Bỏ qua để đến Nội dung
Menu
Câu hỏi này đã bị gắn cờ
2 Trả lời
5307 Lượt xem

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 

Ảnh đại diện
Huỷ bỏ
Tác giả Câu trả lời hay nhất

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


Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất

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.



Ảnh đại diện
Huỷ bỏ
Bài viết liên quan Trả lời Lượt xem Hoạt động
1
thg 10 22
7535
2
thg 1 24
5008
0
thg 7 23
2369
1
thg 8 22
4482
0
thg 2 22
3507