Convert data on AlterField django migration

django, django-migrations, django-models

Solution

Safest way that I always do is:

- create another field with `field_name_new = models.PositiveIntegerField()`

- migrate this new field on production db

- do data migration (convert `field_name` value and move the converted value to field `field_name_new`)

- change your code so that `field_name_new` is used

- deploy the step 4

- delete the field `field_name`

- migrate the step 6 on production db and deploy it (the step 6)

there is only one bad side: you may loose some data in steps 4 and 5. but you can replicate these data to new field basically

Problem

I have a production database and need to keep safe the data. I want to change a Field in model and convert all data inside that database with this change. Old field ``` class MyModel(models.Model): field_name = models.TimeField() ``` Changed field ``` class MyModel(models.Model): field_name = models.PositiveIntegerField() ``` Basically I want to convert the TimeField value (that has a Time object) in minutes. Example: I have in an object `time(hour=2, minute=0, second=0)` and I want to convert that field value in all database table to `120` when I apply the migrate.

Original source