如何重命名Django应用并将数据从一个应用迁移到另一个 [英] How to rename a Django app and migrate data from an app to the other
本文介绍了如何重命名Django应用并将数据从一个应用迁移到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为 app1
的Django应用,其中包含模型和迁移文件.我将此应用程序重命名为 app2
,并修复了所有导入,网址等...现在,迁移文件和表中的数据有问题.
I have a Django app named app1
with models and migrations files.
I renamed this app to app2
and I fixed all imports, urls etc...
I now have a problem with migrations files and data in tables.
如何以正确的方式编写迁移,以确保:
How can I write migrations with the correct way to ensure:
- 新安装=>创建新表
- 更新旧版本=>创建新表,移动数据,删除旧表
注1:有几个带有许多外键的表.
到目前为止,这是我的进步,我不确定自己的进展是否顺利:
Here is my progress so far and I am not sure if I am on the good way:
- 我删除了所有较旧的迁移
- 我运行了
python manage.py makemigrations
来生成新的迁移文件
- I removed all older migrations
- I ran
python manage.py makemigrations
to generate new migrations files
完成这两个步骤后,我可以安装我的应用程序,但是旧版本仍然有问题.
After these 2 steps, I can install my application but I still have problems with old version.
问题:迁移数据的最佳方法是什么?
注意2:我不使用 South
.
推荐答案
我找到了可行的解决方案
I found a solution that's works
- 使用新的外键和新的应用依赖项修复旧的迁移.
- 强制执行旧迁移,以使用旧应用名称创建表,因此在
migrations.CreateModel.options
中添加db_table:'app1_table_name'
- 在每个迁移文件中添加
replaces = [('app1','migration_file_name')]
.这将告诉Django当前迁移(app2.migration_file_name
)将替换旧文件,这将使Django两次执行迁移. - 创建一个迁移文件以使用
migrations重命名表.AlterModelTable
- Fix old migrations with new Foreign Keys and new app dependencies.
- Force old migrations to create tables with old app name, so for that in
migrations.CreateModel.options
, adddb_table: 'app1_table_name'
- In each migration file add
replaces = [('app1', 'migration_file_name')]
. This will tell to Django that current migration (app2.migration_file_name
) will replace the old file, this will prevenent django to execute migrations twice. - Create a migration file to rename tables with
migrations.AlterModelTable
这篇关于如何重命名Django应用并将数据从一个应用迁移到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文