Search code examples
pythondjangomaxlengthdjango-model-field

How to reduce max_length of CharField in Django when data already exists in db


I have a CharField on a Django (1.9) model:

alias = models.CharField(max_length=50)

The app is being used and already has data, and there are objects using all 50 characters already. What is the simplest method to reduce the max_length of this field without getting complaints from my production database when I try to migrate? DB is postgresql if it makes a difference.


Solution

  • I think the right way would be simply go the development python terminal and access all the objects of that particular model and truncate the values for alias as:

     for object in MyModel.objects.all():
          object.alias = object.alias[:REDUCED_LENGTH]
          object.save()
    

    and, the change the max_length in the CharField in your model and run migrations.