我正在使用 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_new
至 book
而不是删除和创建列。 Here's an answer that explains how to change it.
关于django - 如何使用南将数据从一个字段迁移到另一个表中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23530580/