django - 如何使用南将数据从一个字段迁移到另一个表中的字段

标签 django python-2.7 django-south

我正在使用 South 进行架构迁移的 Django 项目。
我有以下场景:

模式

class Book(model.Models):
    name = models.CharField(max_length=255, blank=True)
    bid = models.IntegerField(blank=True, null=True)

class Author(model.Models):
   name = models.CharField(max_length=255, blank=True)
   book_id = models.ForeignKey(Book, null=True, to_field="bid", db_column="bookID")

我想将作者模型更改为以下内容:
class Author(model.Models):
   name = models.CharField(max_length=255, blank=True)
   book = models.ForeignKey(Book, null=True, db_column="book_id")

但没有松散的数据。我想按出价搜索每本书,并将找到的书分配给作者模型中的新字段。

谢谢

最佳答案

您必须进行 3 次迁移。添加新书 FK 的架构迁移,然后是数据迁移,然后是用于删除和重命名字段的架构迁移。

因此,您需要将 models.py 文件更改为:

class Book(model.Models):
    name = models.CharField(max_length=255, blank=True)
    bid = models.IntegerField(blank=True, null=True)

class Author(model.Models):
   name = models.CharField(max_length=255, blank=True)
   book_id = models.ForeignKey(Book, null=True, to_field="bid", db_column="bookID")
   # You don't need the db_column="book_id" since that's what it does at the DB level by default.
   # I'm not sure if things will break if you name it book with another field as book_id.
   book_new = models.ForeignKey(Book, null=True) 

然后运行 ​​python manage.py schemamigration APP_NAME auto然后运行```python manage.py datamigration APP_NAME populate_book_id

然后编辑新创建的数据迁移并循环遍历 Author 实例,使用 book_id 字段设置新书字段。不要忘记在向后方法中删除 book 字段值。

然后将您的 models.py 文件更改为以下内容:
class Book(model.Models):
    name = models.CharField(max_length=255, blank=True)
    bid = models.IntegerField(blank=True, null=True)

class Author(model.Models):
   name = models.CharField(max_length=255, blank=True)
   # You don't need the db_column="book_id" since that's what it does at the DB level by default.
   book = models.ForeignKey(Book, null=True) 

然后运行 ​​python manage.py schemamigration APP_NAME auto您需要检查最后一次架构迁移以确保它正在重命名 book_newbook而不是删除和创建列。 Here's an answer that explains how to change it.

关于django - 如何使用南将数据从一个字段迁移到另一个表中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23530580/

相关文章:

Django 同步数据库和迁移

Django 1.8 和 MongoDB?

python - Django Python 垃圾收集问题

python - ALLOWED_HOSTS 和 Django

Python写入文件返回空文件

python - 如何将 python 中的反斜杠命令转换为在 Linux 上运行

python - 将字段添加到生产环境中现有的 django 应用程序

python - 同时增加数据库计数器

python - 在 Pandas 中使用正则表达式的多重模式

在团队中工作时 Django South 迁移冲突