Siirry sisältöön
Menu
Sinun on rekisteröidyttävä, jotta voit olla vuorovaikutuksessa yhteisön kanssa.
Tämä kysymys on merkitty
2 Vastaukset
9669 Näkymät

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
Hylkää
Paras vastaus

Hi

Try this

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

]
Avatar
Hylkää
Tekijä

Thx.

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

Paras vastaus

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
Hylkää
Tekijä

I like both your suggestions.

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

Aiheeseen liittyviä artikkeleita Vastaukset Näkymät Toimenpide
3
toukok. 24
40442
6
jouluk. 23
65007
1
maalisk. 19
9862
0
helmik. 16
4
0
jouluk. 15
3200