This question has been flagged
4 Replies
7861 Views


I have tried unique sql_constaints using two different methods using flower brackets {} or square brackets [].

Both works fine.

Which one is correct?

_sql_constraints = {

('email_uniq', 'unique(email)', ' Please enter Unique Email id.')

}

(or)

_sql_constraints = [

('email_uniq', 'unique(email)', ' Please enter Unique Email id.')

]

P.S: But when I want to use more than a single constraint it only accepting square brackets [] like this.

_sql_constraints = [

('email_uniq', 'unique(email)', ' Please enter Unique Email id.')

('contact_uniq', 'unique(contact)', ' Please enter Unique Mobile no.')

]

What is the reason behind it.

Avatar
Discard
Best Answer

The _add_sql_constraints method is responsible for adding/removing constraints in postgres table/column whenever you install or upgrade module. Below is the sample code for that method

 def _add_sql_constraints(self, cr):
    for (key, con, _) in self._sql_constraints:
    conname = '%s_%s' % (self._table, key)

In python, we call {()} -> set of tuple, [()] -> list of tuple.

The above mentioned method will look only for iteration no matter what set of tuples or list of tuples. So both the format you mentioned above will work. But you need to stick with the standard list of tuples because set will remove duplicates.

Eg:

a = [('a','b','c'), ('a','b','c')]
print a
b = {('a','b','c'), ('a','b','c')}
print b


Avatar
Discard
Best Answer

Here is an example:

_sql_constraints = [

('convention_prime_id_unique', 'UNIQUE(convention_id,prime_id)',

'Each convention has its unique primes'),

]

You have to use [].

And if you have more than one, you should do like this:


_sql_constraints = [

('prime_id_unique', 'UNIQUE(company_ids,company_convention_prime_id)',

'Each prime_id is unique'),

]

_sql_constraints = [

('company_convention_id_unique', 'UNIQUE(company_convention_prime_id,prime_id)',

'Each company_ids must have its own prime_id'),

]

PS: Those are examples in a module that i have created and it works perfectly :)

Try it and please vote if its fine ;)


Avatar
Discard

Here is a useful link: http://blog.octo.com/en/first-steps-with-openerp/

Author

But I found this : _sql_constraints = [ ('name_uniq', 'unique (name)', 'The name of the country must be unique !'), ('code_uniq', 'unique (code)', 'The code of the country must be unique !') ] for using multiple number of sql_constraints. I think you're wrong.

I am not wrong because i gave you an example that functions correctly in my session.

Author

Okay, sorry. I mean that, _sql_constraints are created in both the way by using [] or {}. I didn't means to say you're wrong.

Its not a problem friend ;) The essential thing is that you understand it and you get the way to solve your problem and increase your knowledge in the ODOO world :) Nice Chance!!!!