Django 1.9 drop foreign key in migration

前端 未结 3 830
Happy的楠姐
Happy的楠姐 2020-12-30 09:13

I have a Django model that has a foreign key to another model:

class Example(models.Model)
   something = models.ForeignKey(SomeModel, db_index=True)
         


        
3条回答
  •  旧巷少年郎
    2020-12-30 09:23

    See SeparateDatabaseAndState. It allows you to specify a Django (state) part of the migration separately from the database part of the migration.

    1. Amend the field in your models file.
    2. Create the migration, as normal. You will end up with something like:

      class Migration(migrations.Migration):
      
          dependencies = [
              ('my_app', '0001_whatever.py'),
          ]
      
          operations = [
              migrations.AlterField(
                  model_name='example',
                  name='something',
                  field=models.CharField(max_length=255, null=True)),
              ),
          ]
      
    3. Now manually amend this to:

      class Migration(migrations.Migration):
      
          dependencies = [
              ('my_app', '0001_whatever.py'),
          ]
      
          state_operations = [
              migrations.AlterField(
                  model_name='example',
                  name='something',
                  field=models.CharField(max_length=255, null=True)),
              ),
          ]
          operations = [
              migrations.SeparateDatabaseAndState(state_operations=state_operations)
          ]
      

    Note that you are not specifying any database_operations argument, so the Django relationships are amended, but the database data is unchanged.

    Needless to say: take a backup before you try this.

提交回复
热议问题