Skip to Content
Menu
Musisz się zarejestrować, aby móc wchodzić w interakcje z tą społecznością.
To pytanie dostało ostrzeżenie
2 Odpowiedzi
10234 Widoki

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.

Awatar
Odrzuć
Najlepsza odpowiedź

Hi

Try this

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

]
Awatar
Odrzuć
Autor

Thx.

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

Najlepsza odpowiedź

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.

Awatar
Odrzuć
Autor

I like both your suggestions.

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

Powiązane posty Odpowiedzi Widoki Czynność
3
maj 24
41251
6
gru 23
65998
1
mar 19
10508
0
lut 16
4
0
gru 15
3485