简体   繁体   中英

Add validation in models in Odoo

I have a model student with the following fields.

class Student(models.Model):
    _name = "student"
    name = fields.Char(string='Name', required=True)
    nid = fields.Char(string='NID', required=True)

I need to ensure that name contains only within 10-15 alphabets and spaces and that nid starts with a capital letter, followed by 12 numbers and ends with a capital letter . Can this be done directly in the model?

Yes you can add this constrains using the decorator @api.constrains('field1', 'field2') witch will tell Odoo to trigger this method if one of the field (in the list of fields passed) is changed.

and using regular expression (re) module will save a lot of typing in this case.

    import re  # for matching

    class Student(models.Model):
        _name = "student"

        name = fields.Char(string='Name', required=True)

        nid = fields.Char(string='NID', required=True)

        @api.constrains('name')
        def check_name(self):
            """ make sure name 10-15 alphabets and spaces"""
            for rec in self:
                # here i forced that the name should start with alphabets if it's not the case remove ^[a-zA-Z]
                # and just keep:  re.match(r"[ a-zA-Z]+", rec.name)
                if not 10 <= len(rec.name) <= 15 or not re.match(r"^[a-zA-Z][ a-zA-Z]*", rec.name):
                    raise exceptions.ValidationError(_('your message about 10-15 alphabets and spaces'))

        @api.constrains('nid')
        def check_nid(self):
            """ make sure nid starts with capital letter, followed by 12 numbers and ends with a capital letter"""
            for rec in self:
                if not re.match(r"^[A-Z][0-9]{12}[A-Z]$", rec.nid):
                    raise exceptions.ValidationError(_('your message about capital letter, followed'
                                                       'by 12 numbers and ends with a capital letter')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM