南,如何从CharField迁移到ForeignKey?

时间:2013-01-23 21:07:54

标签: django casting django-south database-migration

模特:

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

我可以猜测在从字符串转换为int期间发生了错误,但是如何避免这种情况并完成迁移呢?

它有什么不同,我不关心保存表中存储的数据。

1 个答案:

答案 0 :(得分:4)

如果您手动编辑前进功能:

重命名列:

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
""")

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