我正在使用南方进行模式迁移的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")
但没有松散的数据。我想按出价搜索每本书,并在作者模型中将找到的那个分配给新字段。
由于
答案 0 :(得分:4)
您必须进行3次迁移。一个schemamgiration,它添加新书FK,然后是数据迁移,然后是一个schemamigration来删除和重命名字段。
因此,您想要将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字段的新书字段。不要忘记在向后方法中删除书籍字段值。
然后将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.