3

I have been battling with this for a while. none of the two options are working neither were they giving errors. i commented the pythonic constrain method for you to see.

code snippet:

class house_development(models.Model):
    _name = 'house.development'
    _description = 'Development'
    _inherit = ["mail.thread"]

    name = fields.Char(string="Name", required=True, track_visibility='onchange')
    description = fields.Text(string="Description", track_visibility='onchange')

    # @api.one
    # @api.constrains('name')
    # def _identify_same_name(self):
    #     for record in self:
    #         if record.name in self:
    #             raise exceptions.ValidationError("There is another development/project with the same name: %s" % record.name)

    _sql_constraints = [
        ('name_unique',
         'UNIQUE(name)',
         "There is another development/project with the same name"),
    ] 
James Z
  • 12,209
  • 10
  • 24
  • 44
Ropo
  • 144
  • 1
  • 13

1 Answers1

2

It should be like that,

@api.multi
@api.constrains('name')
def _identify_same_name(self):
    for record in self:
        obj = self.search([('name','=ilike',record.name),('id','!=',record.id)])
        if obj:
            raise exceptions.ValidationError("There is another development/project with the same name: %s" % record.name)

You need to search for the same name but not with the same id.

And for database unique constrains you may add like that.

_sql_constraints = [
    ('name_unique', 'unique(name)', 'There is another development/project with the same name!!!'),
] 

Database constrains will not be added if there are duplicate name in table. Sql constrains will apply only if the rule is not violated by the existing data. I think in your case that's the point with Sql constrains. And make sure for that you need to upgrade module. first check duplicate records in database by firing that query.

Select name, count(*) from table_name 
group by name
having count(*) > 1;

Available operators in domain in odoo Click to see more.

  • Thanks so much Emipro Tech, it works but i realised that if i input 'house' and 'House', it bypass the constrains and get saved. How can i include this case sensitivity in the code? Secondly, why did you use @api.multi instead of @api.one? – Ropo Jul 21 '17 at 11:58
  • Thanks real good man.....why did you use @api.multi instead of @api.one? – Ropo Jul 21 '17 at 12:27
  • If you use @api.one then in self only one record will be available while you bulk update then multiple records will be there in self. – Emipro Technologies Pvt. Ltd. Jul 21 '17 at 12:28