Django:保存唯一值而不复制它

a6b3iqyw  于 2022-11-18  发布在  Go
关注(0)|答案(2)|浏览(104)

我试图在数据库中保存唯一的名称,但问题是我可以用不同的字母保存相同的名称,例如我可以保存(IT,it,iT,It),我不想这样保存它。

型号:

class Service(models.Model):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=127, unique=True, null=False, blank=False) # that field
    is_active = models.BooleanField(default=True)
    is_deleted = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(
        "accounts.User",
        on_delete=SET_NULL,
        blank=False,
        null=True,
        related_name="service_created_by",
    )

    def __str__(self):
        return f"{self.name}"
vwkv1x7d

vwkv1x7d1#

一个非常简单的解决方案:

class Service(models.Model):
    name = models.CharField(max_length=50, unique=True)
    ....

    def clean(self):
        self.name = self.name.capitalize()
pxq42qpu

pxq42qpu2#

这个帮了我

class Service(models.Model):
    name = models.CharField(max_length=50, unique=True, null=False, blank=False)
    ....

    class Meta:
        constraints = [
            models.UniqueConstraint(Lower("name"), name="unique_name"),
        ]

    def clean(self):
        self.name = self.name.capitalize()

相关问题