Skip to Content
Meniu
Trebuie să fiți înregistrat pentru a interacționa cu comunitatea.
Această întrebare a fost marcată
2 Răspunsuri
4883 Vizualizări

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!

Imagine profil
Abandonează

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

Cel mai bun răspuns



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



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


Thanks

Imagine profil
Abandonează
Cel mai bun răspuns

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

Imagine profil
Abandonează