Change column type using django migration

Consider this structure:

some_table(id: small int) 

and I want to change it to this:

 some_table(id: string) 

Now I am doing this with three migrations:

  • Create a new _id column with type string
  • (datamigration) Copy data from id to _id with string conversion
  • Delete id and rename _id to id

Is there a way to do this with just one migration?

+5
source share
1 answer

You can directly change the column type from int to row. Note that if sql strict mode is not turned on, integers will be truncated to the maximum row length, and data may be lost, so always back up and choose max_length , which is high enough. In addition, the migration cannot be easily undone (sql does not directly support changing the row column to int column), so backup is really important in this.

Django pre 1.7 / South

You can use db.alter_column . First, create a hyphenation, but do not apply it yet, or you will lose data:

 >>> python manage.py schemamigration my_app --auto 

Then change the forwards method to this:

 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.') 

This will change the column to match the new CharField field. Now apply the migration, and you're done.

Django 1.7 You can use the AlterField operation to modify a column. First create an empty migration:

 >>> python manage.py makemigrations --empty my_app 

Then add the following operation:

 class Migration(migrations.Migration): operations = [ migrations.AlterField('some_model', 'id', models.CharField(max_length=255)) ] 

Now start the migration and Django will change the field according to the new CharField .

+7
source

Source: https://habr.com/ru/post/1208679/


All Articles