Django model - set default charfield in lowercase

天大地大妈咪最大 提交于 2020-11-26 10:24:13

问题


How to set default charfield in lowercase? This is my model:

class User(models.Model):
    username = models.CharField(max_length=100, unique=True)
    password = models.CharField(max_length=64)
    name = models.CharField(max_length=200)
    phone = models.CharField(max_length=20)
    email = models.CharField(max_length=200)

    def __init__(self, *args, **kwargs):
        self.username = self.username.lower()

I tried the __init__ but it doesn't work. I want to make the username in lowercase every time new record saved. Thanks.


回答1:


Just do it in the save method. ie, override the save method of Model class.

def save(self, *args, **kwargs):
    self.username = self.username.lower()
    return super(User, self).save(*args, **kwargs)



回答2:


While overwriting save() method is a valid solution. I found it useful to deal with this on a Field level as opposed to the Model level by overwriting get_prep_value() method.

This way if you ever want to reuse this field in a different model, you can adopt the same consistent strategy. Also the logic is separated from the save method, which you may also want to overwrite for different purposes.

For this case you would do this:

class NameField(models.CharField):
    def __init__(self, *args, **kwargs):
        super(NameField, self).__init__(*args, **kwargs)

    def get_prep_value(self, value):
        return str(value).lower()

class User(models.Model):
    username = models.CharField(max_length=100, unique=True)
    password = models.CharField(max_length=64)
    name = NameField(max_length=200)
    phone = models.CharField(max_length=20)
    email = models.CharField(max_length=200)



回答3:


def save(self, force_insert=False, force_update=False):
        self.YourFildName = self.YourFildName.upper()
        super(YourFomrName, self).save(force_insert, force_update)


来源:https://stackoverflow.com/questions/36330677/django-model-set-default-charfield-in-lowercase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!