gpt4 book ai didi

django - Django 中的 unique_together 不起作用

转载 作者:行者123 更新时间:2023-12-03 05:24:37 26 4
gpt4 key购买 nike

unique_together 不起作用,它只在第一个字段上设置唯一约束并忽略第二个字段。有什么办法可以强制执行唯一约束吗?

class BaseModel(models.Model):

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
deleted = models.DateTimeField(db_index=True, null=True, blank=True)
last_modified_at = models.DateTimeField(auto_now=True)

class Meta:
abstract = True


class Book(BaseModel):
first_form_number = models.CharField(max_length=8)

class Meta:
unique_together = (("first_form_number", "deleted"),)

最佳答案

只要创建了正确的唯一索引,您的模型就能正常工作:

$ python manage.py sqlmigrate app 0001_initial
...
CREATE UNIQUE INDEX "app_base_slug_version_a455c5b7_uniq" ON "app_base" ("slug", "version");
...

(预计您的应用程序名称是“app”)

我必须大致同意user3541631的回答。一般来说,它取决于数据库,但 Django 直接支持的所有四个数据库引擎都是类似的。他们期望“空值在唯一列中是不同的”(请参阅 NULL Handling in SQLite Versus Other Database Engines )

我验证了您的问题,无论是否为空:

class Test(TestCase):
def test_without_null(self):
timestamp = datetime.datetime(2017, 8, 25, tzinfo=pytz.UTC)
book_1 = Book.objects.create(deleted=timestamp, first_form_number='a')
with self.assertRaises(django.db.utils.IntegrityError):
Book.objects.create(deleted=timestamp, first_form_number='a')

def test_with_null(self):
# this test fails !!! (and a duplicate is created)
book_1 = Book.objects.create(first_form_number='a')
with self.assertRaises(django.db.utils.IntegrityError):
Book.objects.create(first_form_number='a')

如果您愿意手动编写迁移来创建两个特殊的部分唯一索引,则可以为 PostgreSQL 提供解决方案:

CREATE UNIQUE INDEX book_2col_uni_idx ON app_book (first_form_number, deleted)
WHERE deleted IS NOT NULL;

CREATE UNIQUE INDEX book_1col_uni_idx ON app_book (first_form_number)
WHERE deleted IS NULL;

参见:

关于django - Django 中的 unique_together 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45881556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com