[英]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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.