【问题标题】:South, how to migrate from CharField to ForeignKey?南方,如何从 CharField 迁移到 ForeignKey?
【发布时间】:2013-01-07 12:05:48
【问题描述】:

型号:

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 的过程中,但我怎样才能避免这种情况并完成迁移?

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

【问题讨论】:

  • 由于您不想保留数据,因此您可以在一次迁移中删除整个模型,然后在后续迁移中使用外键重新添加它。

标签: django casting django-south database-migration


【解决方案1】:

如果您手动编辑转发功能:

重命名列:

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

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

【讨论】:

    猜你喜欢
    • 2019-07-09
    • 2021-07-19
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 2011-12-14
    • 2011-10-30
    相关资源
    最近更新 更多