首页 > 解决方案 > 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()

标签: djangodjango-models

解决方案


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 !!!).


推荐阅读