案例不敏感Charfield在django模型 [英] Case insensitive Charfield in django models
问题描述
我正在尝试实现一个类别模型,其中name具有 unique = True
,
,但实际上我仍然可以添加与不同情况相同的类别名称。 p>
ie我有一个名为Food
的类别我仍然可以添加食物,食物,fOod,FOOd
他们有任何哲学背后吗?或者它是一项正在进行的工作。
如果我想到类别食品,现实世界中的原因,它总是食物,无论在什么情况下,它都会提及自己。
提前谢谢你看这个。
回答我自己的问题:
可以在我的模型上有干净的方法。所以我添加了
class Category(models.Model):
name = models.CharField(max_length = 200,unique = true)
def clean(self):
self.name = self.name.capitalize()
它正在大写第一个字母,然后由保存
方法处理,该方法调用 validate_unique
方法来提高错误。
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.
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.
这篇关于案例不敏感Charfield在django模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!