skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

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

  2. A very simple solution:

    class Service(models.Model):
        name = models.CharField(max_length=50, unique=True)
        ....
    
        def clean(self):
            self.name = self.name.capitalize()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search