如何在Django中迁移模型至其他应用并修改生成模型名(不删表)
Django跨App迁移模型并保留数据的实现方案
核心问题
直接移动模型文件时,Django会自动生成删除原App模型+重建新App模型的迁移,导致数据丢失。我们需要通过自定义迁移实现:
- 将
app/models/example迁移到other_app/models/example - 数据库表名从
app_example改为other_app_example - 全程保留原有数据
分步操作
1. 先重命名数据库表(关键前置步骤)
不要先移动模型!先在原app的Example模型中指定目标表名,生成迁移并执行:
# app/models/example.py class Example(models.Model): # 你的字段定义(保持不变) class Meta: # 强制指定新表名 db_table = 'other_app_example'
执行命令生成并应用迁移:
python manage.py makemigrations app python manage.py migrate app
这一步会把数据库中app_example表重命名为other_app_example,数据完全保留。
2. 移动模型文件到目标App
将app/models/example.py剪切到other_app/models/example.py,删除原文件。
- 确保
other_app已添加到项目settings.py的INSTALLED_APPS中 - 如果
other_app/models目录有__init__.py,可以添加from .example import Example方便导入(可选)
3. 修改自动生成的迁移文件
执行makemigrations命令,Django会自动生成两个迁移文件:
app/migrations/000X_remove_example.py:标记原App删除Example模型other_app/migrations/0001_initial.py:标记新App创建Example模型
修改原App的删除迁移
打开app/migrations/000X_remove_example.py,清空operations列表(不需要实际删除任何表):
from django.db import migrations class Migration(migrations.Migration): dependencies = [ # 替换为你之前重命名表的迁移文件名,比如('app', '0002_example_db_table') ('app', '0002_example_db_table'), ] operations = []
修改新App的创建迁移
打开other_app/migrations/0001_initial.py,删除原有的CreateModel操作,替换为一个空SQL操作(仅标记模型存在,不建表):
from django.db import migrations class Migration(migrations.Migration): initial = True dependencies = [] operations = [ # 空SQL,仅用于更新Django迁移状态 migrations.RunSQL("SELECT 1"), ]
4. 应用最终迁移
执行迁移命令,更新Django的迁移状态:
python manage.py migrate
这一步不会修改数据库,仅告诉Django:原App的Example已移除,新App的Example已存在。
5. 清理模型配置(可选)
在other_app/models/example.py中可以去掉db_table设置,让Django自动使用默认表名other_app_example(和我们已重命名的表一致):
# other_app/models/example.py class Example(models.Model): # 你的字段定义(保持不变) class Meta: # 可选:若Django未自动识别App标签,手动指定 app_label = 'other_app' # 移除db_table,使用默认命名规则
内容的提问来源于stack exchange,提问作者Lirit
相关产品推荐
相关产品推荐

