我有一个名为Locations
的django应用,其models.py
有2个型号:
class City(models.Model):
...
class Country(models.Model):
...
我做了python manage.py schemamigration Locations --initial
然后python manage.py migrate Locations
。一切都很好。
然后我向City
添加了2个字段,并python manage.py schemamigration Locations --auto
,并说:
然后当我做python manage.py migrate Locations
时,我得到了:
Running migrations for Locations:
- Migrating forwards to 0003_auto__del_field_country_cover_image__add_field_city_lng__add_field_cit.
> Locations:0001_initial
FATAL ERROR - The following SQL query failed: CREATE TABLE "Locations_country" ("id" serial NOT NULL PRIMARY KEY, "name" varchar(100) NOT NULL UNIQUE, "slug" varchar(50) NOT NULL, "image" varchar(100) NOT NULL, "flag" varchar(100) NOT NULL)
The error was: relation "Locations_country" already exists
Error in migration: Locations:0001_initial
DatabaseError: relation "Locations_country" already exists
我总是不断收到此错误。我做错了吗?
然后我做了python manage.py migrate Locations 0003 --fake
,这是输出:
- Soft matched migration 0003 to 0003_auto__del_field_country_cover_image__add_field_city_lng__add_field_cit.
Running migrations for Locations:
- Migrating forwards to 0003_auto__del_field_country_cover_image__add_field_city_lng__add_field_cit.
> Locations:0001_initial
(faked)
> Locations:0002_auto__add_field_city_lng__add_field_city_ltd
(faked)
> Locations:0002_auto__add_location__add_field_country_cover_image
(faked)
> Locations:0003_auto__del_field_country_cover_image__add_field_city_lng__add_field_cit
(faked)
现在当我python manage.py migrate Locations
时,它说:
Running migrations for Locations:
- Nothing to migrate.
- Loading initial data for Locations.
Installed 0 object(s) from 0 fixture(s)
这两个字段尚未添加。这是怎么回事?什么是添加/删除字段的正确方法?
我已经阅读了基本的南方文档,如果我错过了某些内容,请指向我。
感谢。
答案 0 :(得分:2)
删除0002
和0003
迁移文件。然后通过执行以下操作回滚到0001
:
python manage.py migrate Locations 0001 --fake --delete-ghost-migrations
之后通常运行schemamigration
和migrate
。
(在与OP讨论时,首先清除了0002
和0003
从未反映到数据库,因此从磁盘中删除这些迁移文件没有坏处。