如何删除 Django 模型而不是数据库?

How to delete the Django model but not the database?

我是 运行 使用 Django 的生产服务器。我想删除不再需要的模型。迁移使得将它们应用到数据库变得容易。但是,我不想删除到目前为止积累的数据库。有没有办法认为迁移管理器已经被删除而不实际删除数据库?

您需要的是带有 --fake 选项的 运行 migrate 管理命令。

--fake

Marks the migrations up to the target one (following the rules above) as applied, but without actually running the SQL to change your database schema.

This is intended for advanced users to manipulate the current migration state directly if they’re manually applying changes; be warned that using --fake runs the risk of putting the migration state table into a state where manual recovery will be needed to make migrations run correctly.

更多解释可以参考Django document

有两种基本方法:改变您 运行 migrate 的方式,或者改变迁移本身。

如果这是对现有数据库的一次性更改,那么您应该使用 --fake 选项简单地 运行 migrate

但是,如果您希望将其应用得更广泛,--fake 方法就太脆弱了。您必须始终记住 运行 将此迁移与其他有丢失数据风险的迁移分开。

在这种情况下,最好自行编辑迁移。具体来说,您可以将仅记录删除的 DeleteModel operation into a RunSQL 操作转换为已使用 state_operations 参数完成。

走哪条路可能取决于这个问题的答案:如果您要从头开始创建数据库,您希望未使用的 table 仍然存在,还是不存在?如果是这样,请编辑迁移文件。如果不是,运行 每个现有数据库一次 --fake.