fixing null text fields in Django models
Let's say that you observe a text field with null=True in a Django model. You, of course, are not responsible for the mistake because you read the docs and know that this is discouraged by Django because of the terrible performance impact.
To make things worse, some empty values are already in the database, represented as NULL so they'll need to be converted to the empty string before changing the field type. Luckily, the app in question is managed by South so you can go ahead and change the model, removing the null=True bit, then start a migration:
- ./manage.py startmigration myapp 'myfield_not_null' --auto
Before applying it, we need to edit the migration file (let's say myapp/migrations/0004_myfield_not_null.py) and do the data transformation:
- # at the beginning of forwards()
- orm.MyModel.objects.filter(myfield__isnull=True).update(myfield='')
- # ....
- # at the end of backwards()
- orm.MyModel.objects.filter(myfield='').update(myfield=None)
This insures that a backwards migration will also be possible. Good. Now that that data conversion is handled, let's apply the migration:
- ./manage.py migrate myapp



Leave a Comment :