syabro
syabro

Reputation: 1887

Django migrations change field type

I've a FK to some model

class A(models.Model):
    b = models.FK(to=B)

I need to change it to IntegerField so it'll look like

class A(models.Model):
    b_id = models.IntegerField()

How can I add new migration without really changing anything in DB?

Upvotes: 2

Views: 2433

Answers (1)

catavaran
catavaran

Reputation: 45575

Create a migration which will change the field type and then will rename the field:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations


class Migration(migrations.Migration):

    dependencies = [
        ('app', '000X_the_name_of_prev_migration'),
    ]

    operations = [
        migrations.AlterField(
            model_name='a',
            name='b',
            field=models.IntegerField(),
            preserve_default=True,
        ),
        migrations.RenameField(
            model_name='a',
            old_name='b',
            new_name='b_id',
        ),
    ]

In fact at SQL level there will be two renames of the column b_id -> b and b -> b_id but the data in this column will be preserved.

Upvotes: 2

Related Questions