0
votes

How in custom module odoo 9 before insert new record in database, check is record exists?

For example:

If in table project.task we have name "PARIS" and date_deadline "2017-01-01" in code below I need warning before execute...

vals = {'name': 'PARIS','date_deadline': '2017-01-01']}
create_new_task = http.request.env['project.task'].create(vals)

Or maybe try get count from project.task where name='PARIS' and date_deadline='2017-01-01' before click on button save!

Any simple solution?

@api.one
@api.constrains('date','time') #Time is Many2one
    def _check_existing(self):
        count = self.env['test.module'].search_count([('date','=',self.date),('time','=',self.time.id)])
        print(self.date)  #2017-01-01
        print(self.time.id) #1
        if(count >= 1):
            raise ValidationError(_('DUPLICATE!'))

After try insert new record in database where is date = 2017-02-02 and time = 1 get this message:

duplicate key value violates unique constraint "test_module_time_uniq" DETAIL: Key (time)=(1) already exists.

Time exist but date is different! I need constrains for 2 value! In databse I have only one row where is date = 2017-01-01 and time = 1

2
You have defined an sql unique constraint on the time field (test_module_time_uniq). You just need to remove it, and it should work.dgeorgiev

2 Answers

2
votes

if you want to prevent duplicated record use sql_constrains

class ModelClass(models.Model):
    _name = 'model.name'
    # your fields ...

    # add unique constraints 
    sql_constraints = [
            ('name_task_uniq', 'UNIQUE (name,date_deadline)',  'all ready got a task with this name and this date')
        ]

    # or use api.constrains if you constrains cannot be don in postgreSQL
    @api.constrains('name', 'date_deadline')
    def _check_existing(self):
        # add you logic to check you constrain  

duplicate key value violates unique constraint "test_module_time_uniq" DETAIL: Key (time)=(1) already exists.

This error is thrown by the postgres not odoo you all ready have a unique constrain for time only you need to drop it first

NB: Who added the constrains unique is it you when you where testing you code or is someone else? Answer this by comment ^^

ALTER TABLE project_task DROP CONSTRAINT test_module_time_uniq;
2
votes

You can use something along those lines:

@api.constrains('name', 'date_deadline')
def _check_existing(self):
    # Search for entry with these params, and if found:
        # raise ValidationError('Item already exists')