Как задать уникальные пару полей в django?

Подскажите, пожалуйста, можно ли в django, в настройках модели задать уникальные пару полей?

Аналогия в sql:
CREATE TABLE Customers
( cnum integer NOT NULL,
cname char (10) NOT NULL,
city char (10),
rating integer,
snum integer NOT NULL,
UNIQUE (cnum, snum));
  • Вопрос задан
  • 6464 просмотра
Решения вопроса 1
sim3x
@sim3x
Options.unique_together
Sets of field names that, taken together, must be unique:

unique_together = (("driver", "restaurant"),)
This is a tuple of tuples that must be unique when considered together. It’s used in the Django admin and is enforced at the database level (i.e., the appropriate UNIQUE statements are included in the CREATE TABLE statement).

For convenience, unique_together can be a single tuple when dealing with a single set of fields:

unique_together = ("driver", "restaurant")


class TTest(models.Model):
    t1 = models.IntegerField()
    t2 = models.IntegerField()

    class Meta:
        unique_together = ('t1', 't2')


$python manage.py sql ttest
BEGIN;
CREATE TABLE "ttest_ttest" (
    "id" integer NOT NULL PRIMARY KEY,
    "t1" integer NOT NULL,
    "t2" integer NOT NULL,
    UNIQUE ("t1", "t2")
)
;

COMMIT;
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы