我们实现了一个 LowerCaseCharField。我们很高兴听到更好的实施建议。
from django.db.models.fields import CharField
class LowerCaseCharField(CharField):
"""
Defines a charfield which automatically converts all inputs to
lowercase and saves.
"""
def pre_save(self, model_instance, add):
"""
Converts the string to lowercase before saving.
"""
current_value = getattr(model_instance, self.attname)
setattr(model_instance, self.attname, current_value.lower())
return getattr(model_instance, self.attname)
其实我们喜欢拥有的是:
> modelinstance.field_name="TEST"
> print modelinstance.field_name
'test'
当前实现仅在保存时转换为小写。