使用Django迁移更改列类型 [英] Change column type with django migrations
问题描述
考虑以下结构:
some_table(id: small int)
,我想将其更改为:
some_table(id: string)
现在,我通过三个迁移来做到这一点:
Now I do this with three migrations:
- 创建新列
_id
,类型为字符串 - (数据迁移)复制数据从
id
到_id
并通过字符串转换 - 删除ID并重命名
_id
到id
- Create a new column
_id
with type string - (datamigration) Copy data from
id
to_id
with string conversion - Remove id and rename
_id
toid
是否可以仅通过一次迁移来做到这一点?
Is there a way to do this with only one migration?
推荐答案
您可以将列的类型直接从int更改为串。请注意,除非启用了严格的sql模式,否则整数将被截断为最大字符串长度,并且可能会丢失数据,因此请始终进行备份并选择足够高的 max_length
。另外,迁移不容易被撤消(sql不直接支持将字符串列更改为int列),因此备份在这一方面确实很重要。
You can directly change the type of a column from int to string. Note that, unless strict sql mode is enabled, integers will be truncated to the maximum string length and data is possibly lost, so always make a backup and choose a max_length
that's high enough. Also, the migration can't easily be reversed (sql doesn't directly support changing a string column to an int column), so a backup is really important in this one.
Django pre 1.7 / South
您可以使用 db.alter_column
。首先,创建迁移,但尚未应用迁移,否则您将丢失数据:
You can use db.alter_column
. First, create a migration, but don't apply it yet, or you'll lose the data:
>>> python manage.py schemamigration my_app --auto
然后,更改 forwards
方法:
class Migration(SchemaMigration):
def forwards(self, orm):
db.alter_column('some_table', 'id', models.CharField(max_length=255))
def backwards(self, orm):
raise RuntimeError('Cannot reverse this migration.')
这将更改列以匹配新的 CharField
字段。现在,应用迁移即可完成。
This will alter the column to match the new CharField
field. Now apply the migration and you're done.
Django 1.7
您可以使用 AlterField
操作更改柱。首先,创建一个空迁移:
Django 1.7
You can use the AlterField
operation to change the column. First, create an empty migration:
>>> python manage.py makemigrations --empty my_app
然后,添加以下操作:
class Migration(migrations.Migration):
operations = [
migrations.AlterField('some_model', 'id', models.CharField(max_length=255))
]
现在运行迁移,然后运行Django将更改字段以匹配新的 CharField
。
Now run the migration, and Django will alter the field to match the new CharField
.
这篇关于使用Django迁移更改列类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!