Ern*_*sto 5 django django-south python-2.7
我正在使用南方的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")
Run Code Online (Sandbox Code Playgroud)
我想将作者模型更改为以下内容:
class Author(model.Models):
name = models.CharField(max_length=255, blank=True)
book = models.ForeignKey(Book, null=True, db_column="book_id")
Run Code Online (Sandbox Code Playgroud)
但没有松散的数据.我想按出价搜索每本书,并将作者发现的那一个分配给作者模型中的新字段.
谢谢
您必须进行 3 次迁移。添加新书 FK 的 schemamigration,然后是数据迁移,然后是删除和重命名字段的 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)
Run Code Online (Sandbox Code Playgroud)
然后运行python manage.py schemamigration APP_NAME auto
然后运行```python manage.py datamigration APP_NAME populate_book_id
然后编辑新创建的数据迁移并循环遍历 Author 实例,使用 book_id 字段设置新的 book 字段。不要忘记在向后方法中删除 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)
Run Code Online (Sandbox Code Playgroud)
然后运行python manage.py schemamigration APP_NAME auto
您将需要检查最后一个架构迁移,以确保它重命名book_new为book而不是删除和创建列。这是解释如何更改它的答案。
| 归档时间: |
|
| 查看次数: |
1507 次 |
| 最近记录: |