如何在 Django 中设置唯一的字段?

244*_*boy 17 python django

我有一个模型类:

class PysicalServer(models.Model):

    serial_number = models.CharField(max_length=64)  # I want to add the unique
    name = models.CharField(max_length=16)
Run Code Online (Sandbox Code Playgroud)

我知道使用primary_key可以设置唯一,但是serial_number不是我的id字段,我不能使用primary_key,还有其他属性可以设置字段唯一吗?

Mau*_*zar 34

只需添加unique=True serial_number = models.CharField(max_length=64, unique=True)在这里查看更多信息https://docs.djangoproject.com/en/1.11/ref/models/fields/#unique


Eyo*_*nyo 7

正如上面其他 stackoverflowers 提到的,您可以使用unique=True. 但请注意,如果您想设置连接的唯一约束,这将不起作用。例如,如果您希望字段的组合是唯一的,那么您应该使用models.UniqueConstraint如下所示

class Book(models.Model):
    title = models.CharField(max_length=300)
    sub_title = models.CharField(max_length=300)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['title', 'sub_title'], name="%(app_label)s_%(class)s_unique")
        ]

    def __str__(self):
        return self.title
Run Code Online (Sandbox Code Playgroud)


Chr*_*zie 6

关键词unique=True造就title CharField独特。


class Book(models.Model):
    title= models.CharField(max_length=300, unique=True)

    def __str__(self):
        return self.title
Run Code Online (Sandbox Code Playgroud)

http://www.learningabout electronics.com/Articles/How-to-make-a-database-table-field-unique-in-Django.php