Case insensitive Charfield in django models

有些话、适合烂在心里 提交于 2019-12-05 21:56:53

问题


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.


回答1:


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.




回答2:


Setting the column to case-insensitive collation should fix this. You may need to do it at the SQL level.



来源:https://stackoverflow.com/questions/9486811/case-insensitive-charfield-in-django-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!