你如何在django模型中创建一个小写字段?

时间:2018-02-02 02:42:41

标签: django django-models

使用这种方法,我可以将字段保存为小写,但事实并非如此 更改现有模型中的字段(即内存中)。

def get_prep_value(self, value):
    value = super(LowercaseField, self).get_prep_value(value)
    if value is not None:
        value = value.lower()
    return value

我很难搞清楚如何将此字段强制为小写而不覆盖保存并在那里进行更改。但是这会拆分这个小写字段的逻辑。我喜欢这个领域的所有内容。我应该覆盖什么,以便设置此值会强制内存中的小写和数据库中的内容?

我不想更改表单,我希望字段类中包含所有小写逻辑。

我发现了类似的部分工作:

def pre_save(self, model_instance, add):
    """ Returns field's value just before saving. """
    attr =  getattr(model_instance, self.attname)
    if attr is not None:
        attr = attr.lower()
        setattr(model_instance, self.attname, attr)
    return attr

def get_prep_value(self, value):
    value = super(LowercaseField, self).get_prep_value(value)
    if value is not None:
        value = value.lower()
    return value

它有一点代码味道,并且在保存之前没有处理检查值,但是我没有看到如何在没有覆盖实际模型类的setattr并且在模型类中处理它的情况下如何做到这一点本身。

1 个答案:

答案 0 :(得分:1)

You can override the "save" method in Django by adding the following code in your models.py file

def save(self, *args, **kwargs):
    self.yourfiled = self.yourfield.lower()
    return super(ModelsName, self).save(*args, **kwargs)

Of course is possible to handle all params with a loop.

For all existing record you can create a Management command that can convert all strings to lowercase here the docs: Writing custom django-admin commands

If you don't want to change the Save method, just add to the form the "|lower" tag that will be convert all string to lowercase in UI

{{ value|lower }}

Hope this help :)