django - Django - 是否可以将单个模型类拆分为两个模型类,同时保留拆分前的数据?
问题描述
在 Django 中,是否可以将单个模型类拆分为两个模型类,同时保留先前输入的数据?
初始型号:
class Fruit(models.Model):
name = models.CharField(max_length=100)
color = models.CharField(max_length=100)
taste_description = models.CharField(max_length=100)
tasty = models.BooleanField()
拆分模型:
class Fruit(models.Model):
name = models.CharField(max_length=100)
color = models.CharField(max_length=100)
class Fruittaste(models.Model):
fruit = models.ForeignKey(Fruit, on_delete=models.CASCADE)
taste_description = models.CharField(max_length=100)
tasty = models.BooleanField()
解决方案
1/ create your new model, leaving the original unchanged
2/ make a migration to create the model, run it, add it to your version control
3/ create an empty migration for your app, and in this migration write the data migration code
def forward(apps, schema_editor):
# VERY important: don't import the models,
# get them from `app.get_model()`
Fruit = apps.models.get("yourappname", "Fruit")
Fruittaste = apps.models.get("yourappname", "Fruittast")
data = [ Fruittaste(fruit=fruit,taste_description=fruit.tase_description,tasty=fruit.tasty) for fruit in Fruit.objects.all()
]
Fruittaste.objects.bulk_create(data)
class Migration(migrations.Migration):
dependencies = [
('yourappname', '000x_previous_migration'),
]
operations = [
migrations.RunPython(forward),
]
NB: depending on your dataset size, you can also write the new records to db one by one instead of collecting them in a list and send the whole to bulk_create. This will be slower, but it will eat less memory.
NB : You should add a backward migration whenever possible, but in your above case you'd have to arbitrarily choose one of the many possible tastes for each fruit so...
4/ and finally remove the now obsolete fields from Fruit
, make and run the migration etc (nb do no forget to add your migration files to your version cotrol !!!).
推荐阅读
- python-3.x - 二十一点课程
- python - 如何从完整文件路径(字符串)构造 Python3 文件对象
- javascript - 在其他项目数组中查找项目时添加类名
- javascript - 使用 reduce 时遇到 js 语法问题
- statistics - Linkedin API - 获取个人资料统计信息
- kubernetes - 检查应用于 Kubernetes 集群上的 nginx 入口控制器的配置
- python - 如何解决 Python 中的许多 if else 语句?
- go - 如何从 RSA 公钥的字节数组中获取 Little Endian 格式的指数和模数
- python - 将函数装饰器转换为类 Mixin django
- reactjs - React Material UI 下拉菜单图标