Convert data on AlterField django migration

前端 未结 2 1363
隐瞒了意图╮
隐瞒了意图╮ 2020-12-31 09:48

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<

2条回答
  •  醉酒成梦
    2020-12-31 10:25

    In the past, I've always done this with the help of Djangos RunPython operation. Create a custom migration that handles the following.

    1. Change name of field.
    2. Add new field of desired type.
    3. RunPython to handle the logic of converting from one to the other.
    4. Delete old field.


    def migrate_time_to_positive_int(apps, schema_editor):
    
        MyModel = apps.get_model('myapp', 'MyModel')
    
        for mm in MyModel.objects.all():
    
            field_old_time = mm.field_name_old
            field_new_int = field_old_time.total_seconds() / 60
            mm.field_name = field_new_int 
            mm.save()
    
    class Migration(migrations.Migration):
    
        operations = [
            migrations.RenameField(
                model_name='mymodel',
                old_name='field_name',
                new_name='field_name_old',
            ),
            migrations.AddField(
                model_name='mymodel',
                name='field_name',
                field=models.PositiveIntegerField(),
            ),
            migrations.RunPython(migrate_time_to_positive_int),
            migrations.RemoveField(
                model_name='mymodel',
                name='field_name_old',
            )
        ]
    

    field_name_old.total_seconds() / 60 might need to be adjusted, but you get the idea.

提交回复
热议问题