从一个django模型迁移到使用外键引用的两个模型 [英] Migrate from one django model to two models referenced with a foreign key
问题描述
我需要在以下Django模型中外包一些属性:
I need to outsource some of the attribues in the following Django model:
class TextResult(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
text = models.ForeignKey(Text)
# following fields will be in the referenced model
wpm = models.FloatField(default=0.0)
accuracy = models.FloatField(default=1.0,
validators=[MinValueValidator(0.0),
MaxValueValidator(1.0)])
提到具体数据的模型:
class TextResult(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
text = models.ForeignKey(Text)
typing_result = models.ForeignKey(TypingResult)
class TypingResult(models.Model):
wpm = models.FloatField(default=0.0)
accuracy = models.FloatField(default=1.0,
validators=[MinValueValidator(0.0),
MaxValueValidator(1.0)])
问题是数据库中已经有一些数据,所以我必须将数据迁移到新的结构,什么是最简单,最干净的方法来实现?
The problem is, that there is already some data in the database, so I have to migrate the data to the new structure, what is the easiest, cleanest way to achieve that?
推荐答案
我将进行三步迁移。
- 创建新字段
- Create the new fields
1.1。创建 TypingResult
模型和 typing_result = models.ForeignKey(TypingResult,blank = True,null = True)
字段。确保FK是可选的,使其为空白且无效
1.1. Create TypingResult
model and the typing_result = models.ForeignKey(TypingResult, blank=True, null=True)
field. Make sure the FK is optional by making it blank-able and null-able
1.2通过迁移检查点
1.2 Checkpoint by migrating
- 数据迁移
- Data Migration
2.1使用本指南 https://docs.djangoproject.com/en/1.11 / topics / migrations /#data-migrations ,并添加数据迁移说明。
2.1 Create an empty migration using this guide https://docs.djangoproject.com/en/1.11/topics/migrations/#data-migrations and add instructions for data migrations.
2.2数据迁移步骤如下:
2.2 The data migration steps are as follows:
-
迭代通过所有
TextResult
为每个人创建一个TypingResult
与相应的数据
Iterate through all
TextResult
for each of them create aTypingResult
with the corresponding data
通过FK将 TypingResult
链接到 TextResult
2.3运行迁移到检查点
2.3 Run the migration to checkpoint
- 清理
- Cleanup
3.1删除 TextResult
并使ForeignKey不可选。
3.1 Delete the wpm and accuracy fields on the TextResult
and make the ForeignKey non-optional.
3.2运行迁移
结论
这可能全部在1个步骤中完成,但最好是了解发生了什么。另外在 .save()
调用之前添加pdb将允许您检查数据迁移的步骤
This can probably all be done in 1 step, but it's best to understand what is going on. Also adding pdb before a .save()
call will allow you to inspect the steps for the data migration
import pdb; pdb.set_trace()
这篇关于从一个django模型迁移到使用外键引用的两个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!