翼度科技»论坛 编程开发 python 查看内容

odoo 开发入门教程系列-约束(Constraints)

4

主题

4

帖子

12

积分

新手上路

Rank: 1

积分
12
约束(Constraints)

上一章介绍了向模型中添加一些业务逻辑的能力。我们现在可以将按钮链接到业务代码,但如何防止用户输入错误的数据?例如,在我们的房地产模块中,没有什么可以阻止用户设置负预期价格。
odoo提供了两种设置自动验证恒定式的方法:Python约束 and SQL约束。
SQL

参考:与此主题相关的文档可以查看 ModelsPostgreSQL文档
我们通过模型属性_sql_constraints来定义SQL约束,该属性被赋值为一个包含三元组(name, sql_definition, message)的列表,其中name为一个合法的SQL约束名称, sql_definition 为表约束表达式,message为错误消息。
一个简单的示例
  1. class AccountAnalyticDistribution(models.Model):
  2.     _name = 'account.analytic.distribution'
  3.     _description = 'Analytic Account Distribution'
  4.     _rec_name = 'account_id'
  5.     account_id = fields.Many2one('account.analytic.account', string='Analytic Account', required=True)
  6.     percentage = fields.Float(string='Percentage', required=True, default=100.0)
  7.     name = fields.Char(string='Name', related='account_id.name', readonly=False)
  8.     tag_id = fields.Many2one('account.analytic.tag', string="Parent tag", required=True)
  9.     _sql_constraints = [
  10.         ('check_percentage', 'CHECK(percentage >= 0 AND percentage <= 100)',
  11.          'The percentage of an analytic distribution should be between 0 and 100.')
  12.     ]
复制代码
注意:当selling_price为null时,也通过CHECK(selling_price > 0)校验的
修改odoo14\custom\estate\models\estate_property_tag.py,添加SQL约束
  1. class BlogTagCategory(models.Model):
  2.     _name = 'blog.tag.category'
  3.     _description = 'Blog Tag Category'
  4.     _order = 'name'
  5.     name = fields.Char('Name', required=True, translate=True)
  6.     tag_ids = fields.One2many('blog.tag', 'category_id', string='Tags')
  7.     _sql_constraints = [
  8.         ('name_uniq', 'unique (name)', "Tag category already exists !"),
  9.     ]
复制代码
修改odoo14\custom\estate\models\estate_property_type.py,添加SQL约束
  1. ERROR rd-demo odoo.schema: Table 'estate_property_offer': unable to add constraint 'estate_property_offer_check_price' as CHECK(price > 0)
复制代码
重启服务验证
预期效果动画:https://www.odoo.com/documentation/14.0/zh_CN/_images/sql_01.gif

https://www.odoo.com/documentation/14.0/zh_CN/_images/sql_02.gif

Python

参考: 主题关联文档可查看constrains().
SQL约束是确保数据一致性的有效方法。然而,可能需要进行更复杂的检查,这需要Python代码。在这种情况下,我们需要一个Python约束。
Python约束定义为用 constrains()修饰的方法,并在记录集上调用。修饰符指定约束中涉及哪些字段。当修改这些字段中的任何字段时,将自动计算约束。如果不满足该方法的恒定式,则该方法将引发异常:
  1.     _sql_constraints = [
  2.         ('check_expected_price', 'CHECK(expected_price > 0)', 'expected price should be positive.'),
  3.         ('check_selling_price', 'CHECK(selling_price > 0)', 'selling price should be positive.')
  4.     ]
复制代码
一个简单的示例
  1.     _sql_constraints = [('check_tag', 'unique(name)', 'Tag name must be unique !')]
复制代码
练习--添加Python约束

添加售价不能低于预期价格90%的约束
提示: 报价生效前,保持售价为0。你需要对校验进行微调,以便把这个考虑在内。
警告
当和浮点数打交道时,总是使用从 odoo.tools.float_utils导入的float_compare() 和float_is_zero()方法
确保每次售价或者预期价格改变时,自动触发约束
修改odoo14\custom\estate\models\estate_property.py
导入 ValidationError
  1.     _sql_constraints = [('check_name', 'unique(name)', 'Type name must be unique !')]
复制代码
最末尾添加以下代码
  1. from odoo.exceptions import ValidationError
  2. ...
  3. @api.constrains('date_end')
  4. def _check_date_end(self):
  5.     for record in self:
  6.         if record.date_end < fields.Date.today():
  7.             raise ValidationError("The end date cannot be set in the past")
  8.     # all records passed the test, don't return anything
复制代码
重启服务,浏览器中验证
预期效果动画:https://www.odoo.com/documentation/14.0/zh_CN/_images/python.gif

SQL约束通常比Python约束更效率。当性能很重要时,总是首选SQL约束而不是Python约束。

来源:https://www.cnblogs.com/shouke/p/17253382.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具