How to make a constraint on a fields

痞子三分冷 提交于 2019-12-08 12:46:41

问题


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!')]

I'm using odoo 10.


回答1:


Constrains can be of two types.

  • Application Constraints
  • Database Constraints

Database Constraints

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. Constraints name
  2. Constraints, like unique, check unique constraints can be applied to many columns.
  3. Error message

Example:

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

Multiple database constraints can be added together.

Application Constraints

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!")



回答2:


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



回答3:


Small change is in your line and your constrain work correctly

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

you just need to put "vat" in place of "self.env.vat" sql_constrains just needs field name which is going to apply on DB table underneath.



来源:https://stackoverflow.com/questions/44161950/how-to-make-a-constraint-on-a-fields

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!