You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django squashmigrations命令执行后如何回滚其产生的影响

Django squashmigrations 回滚方案

问题原因

执行squashmigrations命令时,Django只会生成一个新的压缩迁移文件,不会修改或删除原有旧迁移文件。新生成的压缩迁移文件头部带有replaces属性,会列出所有被它合并的旧迁移名,Django迁移加载器读取到这个属性后,会自动把这些旧迁移标记为「已被替代」,不再将其识别为独立的可用迁移节点,因此执行指向旧迁移的migrate命令时会抛出找不到迁移的错误。

复现示例

前置状态:myapp应用下0001~0004共4个迁移均已完成数据库应用,执行压缩命令:

$ ./manage.py squashmigrations myapp 0004
Will squash the following migrations:
 - 0001_initial
 - 0002_some_change
 - 0003_another_change
 - 0004_undo_something
Do you wish to proceed? [yN] y
Optimizing...
  Optimized from 12 operations to 7 operations.
Created new squashed migration /home/andrew/Programs/DjangoTest/test/migrations/0001_squashed_0004_undo_something.py
  You should commit this migration but leave the old ones in place;
  the new migration will be used for new installs. Once you are sure
  all instances of the codebase have applied the migrations you squashed,
  you can delete them.

此时尝试执行命令回滚到压缩前的0004版本:

python manage.py migrate myapp 0004_undo_something

会抛出错误:

CommandError: Cannot find a migration matching'myapp/migrations/0004_undo_something.py' from app 'myapp'

回滚操作步骤

  • 删除squash生成的压缩迁移文件,即示例路径下的0001_squashed_0004_undo_something.py,全程不要改动原有的0001~0004旧迁移文件。
  • 检查数据库中的django_migrations表:
    • 如果执行完squash后没有跑过migrate命令,表中只会保留原有0001~0004的应用记录,不需要做任何修改。
    • 如果squash后误执行过migrate,表中会多出一条压缩迁移的应用记录,直接删除这条记录即可,不需要修改数据库表结构——压缩迁移的操作逻辑和原有迁移完全一致,不会产生额外的结构变更。
  • 执行python manage.py showmigrations myapp验证状态,正常情况下0001~0004所有旧迁移都会显示为已应用状态,migrate命令恢复正常,找不到迁移的报错完全消失。

内容的提问来源于stack exchange,提问作者Crypto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 07:36:33