Skip to Content
Меню
Вам необхідно зареєструватися, щоб взаємодіяти зі спільнотою.
Це запитання позначене
2 Відповіді
10412 Переглядів

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.

Аватар
Відмінити
Найкраща відповідь

Hi

Try this

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

]
Аватар
Відмінити
Автор

Thx.

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

Найкраща відповідь

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.

Аватар
Відмінити
Автор

I like both your suggestions.

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

Related Posts Відповіді Переглядів Дія
Remove _sql_constraints Вирішено
3
трав. 24
41472
6
груд. 23
66245
1
бер. 19
10661
0
лют. 16
4
0
груд. 15
3630