在AlterField Django迁移上转换数据 [英] Convert data on AlterField django migration
问题描述
我有一个生产数据库,需要确保数据安全。我想更改模型中的字段,并使用此更改转换该数据库内的所有数据。
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.
旧字段
class MyModel(models.Model):
field_name = models.TimeField()
更改的字段
class MyModel(models.Model):
field_name = models.PositiveIntegerField()
基本上我想在几分钟内转换TimeField值(具有Time对象)。
Basically I want to convert the TimeField value (that has a Time object) in minutes.
示例:我在对象 time(hour = 2,minutes = 0,second = 0)
中我希望在应用迁移时将所有数据库表中的该字段值转换为 120
。
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.
推荐答案
我经常做的最安全的方法是:
Safest way that I always do is:
- 使用
field_name_new = models创建另一个字段.PositiveIntegerField()
- 在生产数据库上迁移此新字段
- 进行数据迁移(转换
field_name
值并将
转换后的值移到字段field_name_new
) - 更改代码,以使
field_name_new
已使用 - 部署步骤4
- 删除字段
field_name
- 在生产数据库上迁移步骤6并进行部署(步骤6)
- 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 fieldfield_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)
只有一个不好的方面:您可以在第4步和第5步中丢失一些数据,但是您可以将这些数据基本上复制到新字段中
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
这篇关于在AlterField Django迁移上转换数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!