Removing SQL Constraints in Odoo 8.0
July 02, 2015
In Odoo 6 & 7 it was easier to remove the Sql constraints, but in Odoo 8.0 it is a little bit complex. For making it simpiler I will be showing how you can get this done.
There are basically two approaches for this,
- First one is to fire a SQL command to remove the constraint directly from the database,
- Second one is by creating a custom module, and removing the constraint.
The option you choose is completely dependent on your requirement.
First Approach : How to remove Constraint from the the Database directly:
1. Note down :
- Table Name.
- Constraint Name.
2. Structure for the the constraint name in the database is
- “TableName”+”_”+”ConstraintName
- e.g.,
- Table Name : product_attribute_value
- Constraint Name : value_company_uniq
- Final : product_attribute_value_value_company_uniq
3. The SQL Command would be :
- ALTER TABLE product_attribute_value DROP CONSTRAINT product_attribute_value_value_company_uniq;
In this approach there can be an issue, unless if that’s your need, and that is,
- First, once you restart the server, those constraints will be applied again.
- Second problem will be if you want to apply the constraint again, and you have entered any data which is violating this constraint, like this,
WARNING SurekhatechDB openerp.models.schema: Table 'product_attribute_value': unable to add 'unique (name,attribute_id)' constraint !
If you want to have it, you should update the records and execute manually:
ALTER TABLE "product_attribute_value" ADD CONSTRAINT "product_attribute_value_value_company_uniq" unique (name,attribute_id).
- The solution for the first problem would be to use the Second Approach defined in this blog.
- The solution for the second problem would be, to go in the database, in the table where these values are entered and remove them manually.
Second Approach : Inheriting the model and removing the constraint:
- In this approach, you will be needing a custom module to be developed.
- Inheriting the model whose constraint needs to be removed.
- And then in _sql_constraints entering the constraint to remove.
EXAMPLE :
class product_attribute_value(osv.osv):
_inherit = 'product.attribute.value'
_sql_constraints = [('value_company_uniq', ' CHECK(1=1)', 'This attribute value already exists !')]
product_attribute_value()
- The value_company_uniq is a constraint that I am taking as an example to remove.
- CHECK(1=1) is to to bypass the constraint, through a True condition.
These two approaches would help you remove any constraint in Odoo.