问题
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'),
]
- Constraints name
- Constraints, like unique, check unique constraints can be applied to many columns.
- 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