Bỏ qua để đến Nội dung
Menu
Câu hỏi này đã bị gắn cờ
2 Trả lời
4900 Lượt xem

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!

Ảnh đại diện
Huỷ bỏ

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

Câu trả lời hay nhất



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



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


Thanks

Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất

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

Ảnh đại diện
Huỷ bỏ