案例不敏感Charfield在django模型 [英] Case insensitive Charfield in django models

查看:106
本文介绍了案例不敏感Charfield在django模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个类别模型,其中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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆