Django QuerySet API 检查这个 id 是否唯一

Django QuerySet API check if is unique for this id

这是我的模型的样子:

class Catalog(models.Model):
    global_id = models.IntegerField(unique=True)
    name = models.CharField(max_length=30)
    short_name = models.CharField(max_length=10)
    description = models.CharField(max_length=200, blank=True)
    version = models.CharField(max_length=10)

    class Meta:
        constraints = [
            models.CheckConstraint(
                check=models.Q(
                //
                CHECK IF VERSION IS UNIQUE FOR THIS PARTICULAR GLOBAL_ID
                //
                ),
                name="%(app_label)s_%(class)s_unique_version",
            )
        ]

如您所见,我需要确保版本模型对于特定 global_id 是唯一的,我只是不知道该怎么做。帮助。

下面的代码允许您对这两个字段设置唯一约束。 请注意,要使其起作用,请从 global_id 字段中删除唯一约束。

class Catalog(models.Model):
    global_id = models.IntegerField(max_length=10)
    version = models.CharField(max_length=10)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=['global_id', 'version'],
                name='unique_global_id_for_version'
            )
        ]
>>> Catalog.objects.create(global_id=80, version=80)
<Catalog: Catalog object (10)>
>>> Catalog.objects.create(global_id=90, version=80)
<Catalog: Catalog object (11)>
>>> Catalog.objects.create(global_id=80, version=80)
django.db.utils.IntegrityError: UNIQUE constraint failed: ...
>>> Catalog.objects.create(global_id=80, version=90)
<Catalog: Catalog object (12)>

上面,当尝试创建带有 global_id=80 的目录时失败了,因为它已经存在于 version=80,但后来可以为目录创建带有 global_id=80 的目录version=90.

The docs for this constraint

根据 the docs,您可以使用 django 3.1 的“唯一”选项:

If True, this field must be unique throughout the table.

This is enforced at the database level and by model validation. If you try to save a model with a duplicate value in a unique field, a django.db.IntegrityError will be raised by the model’s save() method.

这将使您的声明像这样:

version = models.CharField(max_length=10, unique=True)