Home > Enterprise >  Django: saving unique value without duplicate it
Django: saving unique value without duplicate it

Time:11-14

I'm trying to save unique name in the database but the problem I can save the same with different letters, for example I can save (IT, it, iT, It) I don't want to save it like that.

Model:

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}"

CodePudding user response:

A very simple solution:

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

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

CodePudding user response:

this one helped me

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()
  • Related