在AlterField Django迁移上转换数据 [英] Convert data on AlterField django migration

查看:69
本文介绍了在AlterField Django迁移上转换数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个生产数据库,需要确保数据安全。我想更改模型中的字段,并使用此更改转换该数据库内的所有数据。

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:


  1. 使用 field_name_new = models创建另一个字段.PositiveIntegerField()

  2. 在生产数据库上迁移此新字段

  3. 进行数据迁移(转换 field_name 值并将
    转换后的值移到字段 field_name_new

  4. 更改代码,以使 field_name_new 已使用

  5. 部署步骤4

  6. 删除字段 field_name

  7. 在生产数据库上迁移步骤6并进行部署(步骤6)

  1. create another field with field_name_new = models.PositiveIntegerField()
  2. migrate this new field on production db
  3. do data migration (convert field_name value and move the converted value to field field_name_new)
  4. change your code so that field_name_new is used
  5. deploy the step 4
  6. delete the field field_name
  7. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆