2

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}"
Taha Omar
  • 51
  • 1
  • 2
  • does this answer your question - [Case insensitive unique model fields in Django?](https://stackoverflow.com/questions/7773341/case-insensitive-unique-model-fields-in-django) – ilyasbbu Nov 14 '22 at 09:18

2 Answers2

0

A very simple solution:

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

    def clean(self):
        self.name = self.name.capitalize()
ilyasbbu
  • 1,468
  • 4
  • 11
  • 22
  • 1
    thank you for your answer, this one not working for me i tried to save Data, DATA, daTa, and django save it. – Taha Omar Nov 14 '22 at 09:35
0

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()
Taha Omar
  • 51
  • 1
  • 2
  • you re not getting this error `TypeError: __init__() takes 1 positional argument but 2 positional arguments (and 1 keyword-only argument) were given` ? – Hemal Patel Nov 14 '22 at 10:58