Passa al contenuto
Menu
È necessario essere registrati per interagire con la community.
La domanda è stata contrassegnata
2 Risposte
10237 Visualizzazioni

I'm trying to weaken a sql unique constraint.
Let's say I have a Human model with name and gender fields. And the name must be unique.

sql_constraints = [('name_unique', UNIQUE(name), 'Error: Name must be unique!')]

What I want is, that the name has to be unique if the gender is female.
How to achieve that?

Can I do something like:

sql_constraints = [('human_check', CHECK(gender='female' AND UNIQUE(name) OR (gender='male'), 'Error: Females must have unique names!')]

Or should I write a custom constraint?
Any other suggestions? (Like splitting the model into Males and Females)

Thanks.

Avatar
Abbandona
Risposta migliore

Hi

Try this

_sql_constraints = [
    ('name_unique', 'CHECK (gender='female')',  'Error: Name must be unique!'),

]
Avatar
Abbandona
Autore

Thx.

I have not tried that yet, but I'm quite sure this will only allow female humans.

Risposta migliore

Hi, Try this.

_sql_constraints = [
    ('name_unique', 'CHECK (gender='female' AND name IS UNIQUE)',  'Error: Name must be unique!'),
]

Just a guess. Better go for custom _constraint.

Avatar
Abbandona
Autore

I like both your suggestions.

But it seems that your sql constraint is not working (yet, no error).

Post correlati Risposte Visualizzazioni Attività
3
mag 24
41255
6
dic 23
66005
1
mar 19
10513
0
feb 16
4
0
dic 15
3486