预选数据迁移到数据库

Pre-selection of data for migration to the database

在 Django 中是否有任何方法可以在迁移期间或之后用多条记录填充数据库,手动方法除外,或者恢复备份。

例如: 我有一个带有服务的模型,在创建数据库后应该已经有 3 个条目,因为它是一个活页夹。

如何在 Django 中实现这个 2.x?

来自 Data migrations

上的 django 文档

Django can’t automatically generate data migrations for you, as it does with schema migrations, but it’s not very hard to write them. Migration files in Django are made up of Operations, and the main operation you use for data migrations is RunPython.

示例

 from django.db import migrations

 def combine_names(apps, schema_editor):
     # We can't import the Person model directly as it may be a newer
     # version than this migration expects. We use the historical version.
     Person = apps.get_model('yourappname', 'Person')
     for person in Person.objects.all():
         person.name = '%s %s' % (person.first_name, person.last_name)
         person.save()

 class Migration(migrations.Migration):

     dependencies = [
         ('yourappname', '0001_initial'),
     ]

     operations = [
         migrations.RunPython(combine_names),
     ]