6

该模型:

class ListContext(models.Model):
    content = models.CharField(max_length=200, blank=True)

我使用 south 来管理模式迁移。

现在我将以前的模型更改为这个:

from django.contrib.contenttypes.models import ContentType

class ListContext(models.Model):
    content = models.ForeignKey(ContentType, blank=True, null=True)

对于迁移:

$ python manage.py schemamigration --auto page 
 ~ Changed field content on page.ListContext
 + Added index for ['content'] on page.ListContext
Created 0010_auto__chg_field_listcontext_content.py. You can now apply this migration with: ./manage.py migrate page

一切都很好,直到这一点:

$ python manage.py migrate page 
Running migrations for page:
 - Migrating forwards to 0010_auto__chg_field_listcontext_content.
 > page:0010_auto__chg_field_listcontext_content
FATAL ERROR - The following SQL query failed: ALTER TABLE "page_page_listcontext" ALTER
COLUMN "content_id" TYPE integer, ALTER COLUMN "content_id" DROP NOT NULL, ALTER COLUMN
"content_id" DROP DEFAULT;

The error was: column "content_id" cannot be cast to type integer

Error in migration: page:0010_auto__chg_field_listcontext_content

我可以猜到错误发生在从 string 转换为 int 的过程中,但是我怎样才能避免这种情况并完成迁移呢?

有什么区别吗,我不在乎保留存储在表中的数据。

4

1 回答 1

4

如果您手动编辑 forwards 功能:

重命名列:

db.rename_column('sometable', 'content', 'content_old')

然后将您的列添加回来:

db.add_column('sometable', 'content', self.gf('django.db.models.fields.IntegerField')(default=0))

然后通过查找 id 执行更新新字段的查询。

db.execute("""
  UPDATE sometable SET content =
  (SELECT FKTable.id FROM FKTable
  WHERE (FKTable.content = sometable.content_old AND
  sometable.content_old != '')
  OR (FKTable.content = 'none' AND sometable.content_old = '')) --Maybe cut the OR out
""")

然后,您必须做一些花哨的事情才能使向后正常工作。

于 2013-01-23T21:29:40.317 回答