Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 698
mmrs151 Avatar asked Feb 28 '12 17:02

mmrs151


People also ask

Is Django case sensitive?

So, the programmer has told Django explicitly, 'I want case-insensitive comparison', and Django tells MySQL, 'We want default comparison'. This is not field_icontains but rather some field_usingdefaultsettingscontains. So, case-sensitivity is explicitly requested, while case-insensitivity is implied.

What does CharField mean in Django?

CharField is a commonly-defined field used as an attribute to reference a text-based database column when defining Model classes with the Django ORM. The Django project has wonderful documentation for CharField and all of the other column fields.

WHAT IS models CharField in Django?

CharField is generally used for storing small strings like first name, last name, etc. To store larger text TextField is used. The default form widget for this field is TextInput. CharField has one extra required argument: CharField.max_length. The maximum length (in characters) of the field.

What does case insensitive mean?

case insensitive (not comparable) (computer science) Treating or interpreting upper- and lowercase letters as being the same.


1 Answers

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

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

like image 101
mmrs151 Avatar answered Oct 14 '22 04:10

mmrs151