We implemented a LowerCaseCharField. We would be happy to hear better implementation suggestions.
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)
In fact we love to have is:
> modelinstance.field_name="TEST"
> print modelinstance.field_name
'test'
current implementation only converts to lowercase when it is saved.
You may wish to override
to_python, which will allow you to compare non-lowercase strings when doing database lookups. The actual method isget_prep_value, but as that callsto_pythonforCharField, it’s more convenient to override that:Now you can do queries like:
Edit:
Rereading your question, it looks like you want the lowering to take effect immediately. To do this, you’ll need to create a descriptor (a new-style python object with
__get__and__set__methods, see the python docs and the django code for related models) and overridecontribute_to_classin the field to set the model’s field to your descriptor.Here is a full example off the top of my head, which should be reusable for all fields that want to modify the value on setting.