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

后端 未结 11 1674
日久生厌
日久生厌 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:18

    Copied from my answer at https://stackoverflow.com/a/47392970/8971048

    In case you need to move the model and you don't have access to the app anymore (or you don't want the access), you can create a new Operation and consider to create a new model only if the migrated model does not exist.

    In this example I am passing 'MyModel' from old_app to myapp.

    class MigrateOrCreateTable(migrations.CreateModel):
        def __init__(self, source_table, dst_table, *args, **kwargs):
            super(MigrateOrCreateTable, self).__init__(*args, **kwargs)
            self.source_table = source_table
            self.dst_table = dst_table
    
        def database_forwards(self, app_label, schema_editor, from_state, to_state):
            table_exists = self.source_table in schema_editor.connection.introspection.table_names()
            if table_exists:
                with schema_editor.connection.cursor() as cursor:
                    cursor.execute("RENAME TABLE {} TO {};".format(self.source_table, self.dst_table))
            else:
                return super(MigrateOrCreateTable, self).database_forwards(app_label, schema_editor, from_state, to_state)
    
    
    class Migration(migrations.Migration):
    
        dependencies = [
            ('myapp', '0002_some_migration'),
        ]
    
        operations = [
            MigrateOrCreateTable(
                source_table='old_app_mymodel',
                dst_table='myapp_mymodel',
                name='MyModel',
                fields=[
                    ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                    ('name', models.CharField(max_length=18))
                ],
            ),
        ]
    

提交回复
热议问题