在 Odoo 的模型中添加验证
Add validation in models in Odoo
我有一个包含以下字段的模型 student
。
class Student(models.Model):
_name = "student"
name = fields.Char(string='Name', required=True)
nid = fields.Char(string='NID', required=True)
我需要确保 name
只包含 10-15 个字母和空格 并且 nid
以 大写开头字母,后跟 12 个数字,并以大写字母 结尾。这可以直接在模型中完成吗?
是的,您可以使用装饰器添加此约束 @api.constrains('field1', 'field2')
如果其中一个字段(在传递的字段列表中)发生更改,将告诉 Odoo 触发此方法。
在这种情况下,使用正则表达式 (re) 模块将节省大量输入。
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')
我有一个包含以下字段的模型 student
。
class Student(models.Model):
_name = "student"
name = fields.Char(string='Name', required=True)
nid = fields.Char(string='NID', required=True)
我需要确保 name
只包含 10-15 个字母和空格 并且 nid
以 大写开头字母,后跟 12 个数字,并以大写字母 结尾。这可以直接在模型中完成吗?
是的,您可以使用装饰器添加此约束 @api.constrains('field1', 'field2') 如果其中一个字段(在传递的字段列表中)发生更改,将告诉 Odoo 触发此方法。
在这种情况下,使用正则表达式 (re) 模块将节省大量输入。
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')