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 |
--------------------------------
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'])]
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'])]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With