Auto-truncating fields at max_length in Django CharFields

前端 未结 4 964
夕颜
夕颜 2020-12-15 16:40

I have a field that has a max_length set. When I save a model instance, and the field\'s value is greater than max_length, Django enforces that

4条回答
  •  心在旅途
    2020-12-15 17:19

    You could create a custom field that auto-truncates the field (I think this code should work, but double-check it):

    class TruncatingCharField(models.CharField):
        def get_prep_value(self, value):
            value = super(TruncatingCharField,self).get_prep_value(value)
            if value:
                return value[:self.max_length]
            return value
    

    Then, instead of using models.CharField in your models.py file, you'd just use TruncatingCharField instead.

    get_prep_value prepares the value for a field for insertion in the database, so it's the ideal place to truncate.

提交回复
热议问题