【问题标题】:Django migrations -- how do I wipe a model as part of a migration?Django 迁移——如何在迁移过程中擦除模型?
【发布时间】:2021-06-02 19:27:05
【问题描述】:

我有一个工作流程,其中模型是由脚本从也存储在数据库中的一些数据生成的:

SourceData -> management command generates -> Results

当我更改结果模型的生成方式(例如添加新字段)时,我不想设置默认值或更新现有模型,我想删除所有模型并再次运行脚本以重新生成他们与新领域:

Delete all Results -> run management command v2 -> Results (+ new field)

有没有简单的方法来做到这一点?我在网上找到的只是如何通过删除整个数据库来实现这一点,这不是我想要的,我只想删除这个表并重新创建它。

【问题讨论】:

    标签: python django postgresql django-migrations


    【解决方案1】:

    想不出正确的方法,但设法破解它:

    • 从干净的 git 历史记录开始(没有脏文件)——让接下来的步骤更容易
    • 将相关模型重命名为其他名称,例如 Model2
    • 运行 makemigrations
    • 还原除生成的迁移之外的所有更改
    • 对生成的迁移文件重新排序,使DeleteModel 位于CreateModel 之前,并将CreateModel 中正在创建的模型的名称改回原来的模型名称。它应该如下所示:
    class Migration(migrations.Migration):
    
        dependencies = [
            ("<app name>", "<previous migration>"),
        ]
    
        operations = [
            migrations.DeleteModel(
                name="ModelName",
            ),
            migrations.CreateModel(
                name="ModelName",
                fields=[
                    # < all fields of your model >
                ],
                options={
                    # < all meta options of your model >
                },
            ),
        ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-17
      • 2016-01-27
      • 1970-01-01
      • 1970-01-01
      • 2014-06-07
      • 1970-01-01
      • 2020-09-10
      • 2018-12-15
      相关资源
      最近更新 更多