how to handle some field before saving to DB with Lowercase letter ?


First of all, my web site uses Pogesql Database.

Some model field in the data model needs to save to database with lowercase letter .
this scenario includes both doing in the admin page and end-user page.

The key point is that I don’t want to customize too much in the code file. just configure a little bit in the file.

as I research, there is nothing much to refer about this thing in link below.

The link below is a likely way to deal with this issue, but i prefer to do with the other way apart from that.

This link shows 2 options for this issue

  1. With data cleaners in
class SignUpForm(UserCreationForm):
    # your code
    email = forms.EmailField(required=True)
    def clean_email(self):
        data = self.cleaned_data['email']
        return data.lower()
  1. With a custom field:
class EmailLowerField(forms.EmailField):
    def to_python(self, value):
        return value.lower()

In my thought, there are pros and cons.

  1. for “With data cleaners” is suitable for user form ( it is not in admin form).
    2.for “With a custom field” , I am concerned about running makemigration and migrate command to a database problem. it is probable to fail to migrate to database

Are there other ways to deal with my question?

In this case of lower character, there are brand_name in class Brand along with model_name in class Model

Supposing, I fill data in model form model_name=XXt001 , then it is saved as xxt001 instead.

Below is

class Brand(models.Model):
    brand_name=models.CharField(max_length=100,unique=True) # prefer lowercase letter
    def __str__(self):
        return self.brand_name

class Model(models.Model):
    model_name=models.CharField(max_length=100) # want lowercase letter
    def __str__(self):
        return self.model_name

If you want to make sure(*) that the names are stored in the database with lower case letters, you can override the model’s save method to convert those fields to lower case before the save occurs.

*Note: This isn’t perfect. Bulk operations don’t call the save method on the individual rows being created or updated.

Warning: I know you’re not specifically talking about email addresses here, but there’s a real problem with the example that they’re using. According to RFC5321, the semantics of an email address before the domain name (the part before the @) are left to the discretion of that email server. It is perfectly valid for an email server to provide case-sensitive email addresses.
It is not valid to assume that the local component of an email address is case-insensitive.
(And yes, I know of at least one specific case where this is true.)


Thank you.
you recommend me to override save method in the data model, that is good