【问题标题】:Pre-selection of data for migration to the database预选数据以迁移到数据库
【发布时间】:2018-05-29 10:27:49
【问题描述】:

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

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

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

【问题讨论】:

    标签: django django-models django-database


    【解决方案1】:

    来自Data migrations上的django文档

    Django 不能自动为你生成数据迁移,因为它 与模式迁移一样,但编写它们并不难。 Django 中的迁移文件由 Operations 和 main 用于数据迁移的操作是 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),
         ]
    

    【讨论】:

      猜你喜欢
      • 2011-06-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多