Skip to Content
Menu
Dette spørgsmål er blevet anmeldt
2 Besvarelser
4894 Visninger

Hello all,

I have a form for "Fee Head". In that form i have field for "code". I want to make that code field unique. So that when i save one form with code=1, then next time time it should not allow me to save form with that code.?

please help.

Here is my code.


code = fields.Char(string='Code')

_sql_constraints = [
('new_name_uniq',
'UNIQUE (code)',
'Subjects must be unique.')]

Thank you!

Avatar
Kassér

Hello, Please remove duplicate value which is already stored in database and then try to install it again.

Bedste svar



code = fields.Char(string='Reference', index=True, tracking=True)



_sql_constraints = [('unique_code', 'unique(code)', 'La référence doit être unique !')


Thanks

Avatar
Kassér
Bedste svar

Your code is correct but you have to know that if you already have duplicate values in code field the 

SQL Constraints will not applied so you have to check all values of the field Code and fix the duplicate and then upgrade you module again.


Another way you can use Odoo Api  @api.constrains('code')

Example:

The below code to use constrains on product name using Odoo API


class ProductTemplate(models.Model):
_inherit = "product.template"

@api.one
@api.constrains('name')
def _check_unique_name(self):
product = self.search([('id', '!=', self.id) , ('name', '=ilike', self.name)])
if product:
raise ValidationError(_('Product name already exists!'))

Avatar
Kassér