Search code examples
pythonodoounique-constraintodoo-8openerp-8

Unique email field in Odoo v8


I want to set the email from Leads and Contacts unique.

I have tried to change in /usr/lib/python2.7/dist-packages/openerp/models.py file, line 342 from:

_sql_constraints = []

in:

_sql_constraints = [
        ('user_email', 'unique(user_email)', 'Please enter Unique Email'),
]

But is not working.

What is the right approach, please give me a full example, because I am a beginner in Odoo, thank you.


Solution

  • You changed sql constraints on the BaseModel. All models in the system are based on this model. So the effect of this change is to add the constrain to every model in Odoo, most of which doesn't even have user_email field. The result of this could be absolutely disastrous. The only reason your Odoo haven't failed yet is you didn't use the upgrade option, so for now the changes haven't propagate to the database.

    First of all revert the changes immediately. Second of all you are not supposed to ever change Odoo source code directly. For one thing, if you start modifying Odoo's source code you will never be able to update it to a newer version (even with a security update), since this would revert your changes.

    What you should do instead is to create a new module and then use it to extend the module you want to modify:

    class Lead(models.Model):
        _inherit = 'crm.lead'
    
        _sql_constraints = [
                ('user_email', 'unique(user_email)', 'Please enter Unique Email'),
        ]
    

    Note: There was a bug in early versions of Odoo 8 preventing one from changing sql constraints by extending an object. It is now fixed. Make sure you are using the most recent version of Odoo from git. If this is not possible it may be necessary to use a work around.