【问题标题】:How do I revert an unfinished makemigration after adding a non-nullable field(Foreign) and filling it添加不可为空的字段(外国)并填充后,如何恢复未完成的 makemigration
【发布时间】:2021-01-10 19:41:08
【问题描述】:

我犯了一个错误,添加了一个不可为空的字段并用 1 填充。

contest = models.ForeignKey(Contest, on_delete=models.CASCADE)

(比赛为空,新桌)

 >>> python manage.py makemigrations contests
You are trying to add a non-nullable field 'contest' to contestentry without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py
Select an option: 1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
>>> 1

迁移时出现错误,因为模型的表是空的。

>>> python manage.py migrate contests 
psycopg2.errors.ForeignKeyViolation: insert or update on table "contests_contestentry" violates foreign key constraint "contests_contestentr_contest_id_7f53b874_fk_contests_"
DETAIL:  Key (contest_id)=(1) is not present in table "contests_contest".

我删除了该字段并尝试迁移回来,但它没有工作,然后我尝试恢复迁移,但它给出了以下错误:

>>> python manage.py migrate contests 0007_remove_contestentry_nvotes

    Operations to perform:
      Target specific migration: 0007_remove_contestentry_nvotes, from contests
    Running migrations:
      No migrations to apply.
      Your models have changes that are not yet reflected in a migration, and so won't be applied.
      Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.

如何恢复到migration_007,然后在数据库中将该字段设置为空?

【问题讨论】:

    标签: django django-migrations revert


    【解决方案1】:

    您可以通过迁移到以前的迁移来恢复。

    例如,如果您的最后两次迁移是:

    0010_previous_migration
    0011_migration_to_revert
    
    Then you would do:
    
    ./manage.py migrate my_app 0010_previous_migration 
    

    然后您可以删除迁移 0011_migration_to_revert。

    对于空模型:

    contest = models.ForeignKey(Contest, on_delete=models.CASCADE, blank=true)
    

    【讨论】:

    • 我看到了 OP 我收到了错误:您的模型有尚未反映的更改
    • 好的,很抱歉,您是否尝试自己从数据库中删除损坏的对象?
    【解决方案2】:

    我通过删除 appname/migrations 中的迁移解决了这个问题,删除了冲突的代码并再次运行 makemigrations migrate

    【讨论】:

      猜你喜欢
      • 2015-03-16
      • 2014-02-04
      • 2014-06-27
      • 2016-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-09
      相关资源
      最近更新 更多