Search code examples
odooodoo-8odoo-10odoo-9

odoo validate by database


I want to make validation when both field customer_id and project_product_id inserted together and checked with the database and show error if both are the same with the database

My py code is like

_name='crm.project'
customer_id = fields.Many2one('res.partner','Customer')
@api.multi 
@api.constrains('customer_id','project_product_id')
def _check_total_value(self):
    target_list = []
    get_customer_id = self.customer_id
    get_project_product_id = self.project_product_id
self.env.cr.execute('''
                            select * 
                            from crm_project 
                            where customer_id = %s 
                                AND project_product_id = %s
                                
    ''',(get_customer_id,get_project_product_id))
    for target in self.env.cr.dictfetchall():
        target_list.append(target)
    if target_list:
        raise Warning("data duplicate")  

Solution

  • checked with the database and show error if both are the same with the database

    Then you clearly need a UNIQUE constraint in your database.

    Please don't check such things in your python code - there are dozens of cases when something can go wrong, when you're checking data validity in a client application, but not on the database level. More info.

    And that's how to make a database-level unique constraint in Odoo