如何正确地向南方模型添​​加字段?

时间:2013-11-17 23:13:35

标签: django django-south

我有一个名为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,并说:

  • 已在Locations.Country上删除了字段cover_image
  • 在Locations.City上添加了字段lng
  • 在Locations.City上添加了field ltd 创建了0003_auto__del_field_country_cover_image__add_field_city_lng__add_field_cit.py。您现在可以将此迁移应用于:./ manage.py migrate Locations

然后当我做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)

这两个字段尚未添加。这是怎么回事?什么是添加/删除字段的正确方法?

我已经阅读了基本的南方文档,如果我错过了某些内容,请指向我。

感谢。

1 个答案:

答案 0 :(得分:2)

删除00020003迁移文件。然后通过执行以下操作回滚到0001

python manage.py migrate Locations 0001 --fake --delete-ghost-migrations

之后通常运行schemamigrationmigrate

(在与OP讨论时,首先清除了00020003从未反映到数据库,因此从磁盘中删除这些迁移文件没有坏处。