How to move a model between two Django apps (Django 1.7)

后端 未结 11 1690
日久生厌
日久生厌 2020-11-28 17:35

So about a year ago I started a project and like all new developers I didn\'t really focus too much on the structure, however now I am further along with Django it has start

11条回答
  •  伪装坚强ぢ
    2020-11-28 18:00

    This can be done fairly easily using migrations.SeparateDatabaseAndState. Basically, we use a database operation to rename the table concurrently with two state operations to remove the model from one app's history and create it in another's.

    Remove from old app

    python manage.py makemigrations old_app --empty
    

    In the migration:

    class Migration(migrations.Migration):
    
        dependencies = []
    
        database_operations = [
            migrations.AlterModelTable('TheModel', 'newapp_themodel')
        ]
    
        state_operations = [
            migrations.DeleteModel('TheModel')
        ]
    
        operations = [
            migrations.SeparateDatabaseAndState(
                database_operations=database_operations,
                state_operations=state_operations)
        ]
    

    Add to new app

    First, copy the model to the new app's model.py, then:

    python manage.py makemigrations new_app
    

    This will generate a migration with a naive CreateModel operation as the sole operation. Wrap that in a SeparateDatabaseAndState operation such that we don't try to recreate the table. Also include the prior migration as a dependency:

    class Migration(migrations.Migration):
    
        dependencies = [
            ('old_app', 'above_migration')
        ]
    
        state_operations = [
            migrations.CreateModel(
                name='TheModel',
                fields=[
                    ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ],
                options={
                    'db_table': 'newapp_themodel',
                },
                bases=(models.Model,),
            )
        ]
    
        operations = [
            migrations.SeparateDatabaseAndState(state_operations=state_operations)
        ]
    

提交回复
热议问题