如何对字段进行约束 [英] How to make a constraint on a fields

查看:74
本文介绍了如何对字段进行约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对一个字段(TIN)进行控制检查,以便每次创建新客户时,TIN应该是唯一的.如果其他客户拥有该TIN,则必须显示错误消息. 我尝试了以下语法:

I want to put a control check on a field (TIN) so that everytime I create a new customer, the TIN should be unique. If another customer has that TIN, an error message must show up. I tried this syntax:

_sql_constraints=[('uniq_vat', 'UNIQUE(self.env.vat)', 
'It already exists another company with the same TIN!')]

我正在使用odoo 10.

I'm using odoo 10.

推荐答案

约束可以有两种类型.

  • 应用限制
  • 数据库约束

数据库约束

数据库约束将在升级该模块时在数据库级别添加验证.数据库约束是元组列表,其中元组包含三个参数.

Database constraints will add validation at database level while you upgrade that module. Database constraints is list of tuples, in which tuple contains three arguments.

_sql_constraints = [
         ('constrain name', 'unique(field1, field2)', 'error message which you want to raise on constrains violation'),
         ('constrain name', 'constrains defination', 'error message which you want to raise on constrains violation'),
 ]

  1. 约束名称
  2. 约束,如唯一,请检查 唯一的约束可以应用于许多列.
  3. 错误消息
  1. Constraints name
  2. Constraints, like unique, check unique constraints can be applied to many columns.
  3. Error message

示例:

_sql_constraints = [
     ('uniq_vat', 'unique(vat)', 'It already exists another company with the same TIN!'),
 ]

可以将多个数据库约束加在一起.

Multiple database constraints can be added together.

应用约束

应用程序约束用于在记录添加,更新和删除时触发自定义验证.简而言之,如果记录发生任何更改,则将调用您的自定义方法.

Application constraints is used to fire custom validation at the time of record add, update and delete. In short your custom method will be called if any changes happen with record.

如何在代码中定义约束.

How to define constrains in code.

@api.constrains('field1','field2'....)

约束可以一起应用于多个字段,也可以分别定义.

Constrains can be applied to multiple fields together, you can also define it separately.

@api.constrains('vat')
def check_vatnumber(self):
    for record in self:
        obj = self.search([('vat','=',record.vat),('id','!=',record.id)])
        if obj:
            raise Warning("Warning", "It already exists another company with the same TIN!")

这篇关于如何对字段进行约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆