django-modelscase-insensitive

Case insensitive Charfield in django models


I am trying to achieve a category model where name has unique=True, but practically I can still add same category name with different cases.

i.e. I have a category called Food I am still able to add food, FOOD, fOod, FOOd

Is their any philosophy behind this? or it is a work in progress.

Cause in real world if I think of Category Food, it will always be food, no matter what case it has used to mention itself.

Thank you in advance to look at this.


Solution

  • To answer my own question:

    I have found I can have clean method on my model. So I added

    class Category(models.Model):
        name = models.CharField(max_length=200, unique=True)
    
        def clean(self):
            self.name = self.name.capitalize()
            return super().clean()
            
    

    It is capitalising the first letter, which is then handled by the save method, which calls the validate_unique method to raise error.