【发布时间】: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