【问题标题】:How to properly add fields to models with South?如何正确地将字段添加到带有 South 的模型中?
【发布时间】:2013-11-17 23:13:35
【问题描述】:

我有一个名为 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 上添加了字段 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)

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

我已阅读基本的 South 文档,如果我遗漏了什么,请指出我。

谢谢。

【问题讨论】:

  • 在您向 South 运行之前不知何故创建了该表。你跑syncdb了吗?尝试回滚到 0002,从数据库中手动删除 Locations_country 表,然后在 South 运行迁移。
  • 是的,我可能已经运行了 syncdb。如何回滚到 0002?而且我不能删除 Locations_country 因为我有数据。我该怎么办?
  • 您在同步表格后将应用程序转换为南?
  • @AamirAdnan 不,但我必须在迁移后完成syncdb --all
  • 所以 syncdb -all 强制所有表同步,不管南方管理它。现在你已经伪造了所有的迁移,所以现在没有问题了。因为 syncdb --all 已经添加了新字段,所以现在不需要 south 再做一次。

标签: django django-south


【解决方案1】:

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

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

之后正常运行schemamigrationmigrate

(在与 OP 的讨论中,首先明确了 00020003 从未反映到数据库中,因此从磁盘中删除这些迁移文件是没有害处的)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多