Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-truncating fields at max_length in Django CharFields

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 max_length at the database level. (See Django docs on models: http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.CharField.max_length)

However, since I am using Postgres, I receive a DatabaseError exception like this:

DatabaseError: value too long for type character varying(1000) 

I would prefer to instead auto-truncate the value (so I don't have an exception). Now, I can do this manually, but what I would really want is to have all of my models auto-truncate the value. (Not necessarily intelligently. Just cutting it off at the 999th character is fine.)

Should I just write a custom class that imports from models.Model and override the save() method, looping through each _meta.field, checking for the max_length, and then truncating? That seems inelegant and there must be a better way.

like image 213
Samuel Clay Avatar asked Aug 11 '10 15:08

Samuel Clay


2 Answers

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.

like image 127
Jordan Reiter Avatar answered Oct 15 '22 05:10

Jordan Reiter


Why don't you use a TextField? From the manual:

For large amounts of text, use TextField.

like image 29
Frank Heikens Avatar answered Oct 15 '22 07:10

Frank Heikens