Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenERP Unique Constraint

Tags:

python

openerp

I have a table in OpenERP/PostgreSQL with the following columns: name and description.

I added the following validation for unique name:

_sql_constraints = [('unique_name', 'unique(name)', 'A record with the same name already exists.')]

It works fine but it is case sensitive. Currently, it accepts values such as "Mickey", "MICKEY" and "mickey":

Wrong Way:
--------------------------
| name   | description   |
--------------------------
| mickey | not a mouse   |
--------------------------
| MICKEY | not a mouse   |
--------------------------
| Mickey | not a mouse   |
--------------------------

Is there a way to revise the validation code so that it will not allow users to add several values such as "Mickey", "MICKEY" and "mickey"? How can I make the unique key validation case insensitive?

Right Way:
--------------------------------
| name         | description   |
--------------------------------
| mickey       | not a mouse   |
--------------------------------
| mickey mouse | is a mouse    |
--------------------------------
| donald       | is a duck     |
--------------------------------
like image 589
codemickeycode Avatar asked Nov 07 '12 05:11

codemickeycode


2 Answers

For case insensitive constraints check out HERE else you can always use Openerp Constraints instead of SQL .

for openerp Constraints

check the example

def _check_unique_insesitive(self, cr, uid, ids, context=None):
    sr_ids = self.search(cr, 1 ,[], context=context)
    lst = [
            x.FIELD.lower() for x in self.browse(cr, uid, sr_ids, context=context)
            if x.FIELD and x.id not in ids
          ]
    for self_obj in self.browse(cr, uid, ids, context=context):
        if self_obj.FILD and self_obj.FILD.lower() in  lst:
            return False
    return True

_constraints = [(_check_unique_insesitive, 'Error: UNIQUE MSG', ['FIELD'])]
like image 139
Ruchir Shukla Avatar answered Nov 11 '22 11:11

Ruchir Shukla


This way without read all data from database:

def _check_unique_insesitive(self, cr, uid, ids, context=None):

    for self_obj in self.browse(cr, uid, ids, context=context):
        if self_obj.name and self.search_count(cr, uid, [('name', '=ilike', self_obj.name), ('id', '!=', self_obj.id)], context=context) != 0:
            return False

    return True

_constraints = [(_check_unique_insesitive, _('The name must be unique!'), ['name'])]
like image 1
Sergik666 Avatar answered Nov 11 '22 10:11

Sergik666