Django在迁移后插入默认数据

Dha*_*oon 13 django

我希望我的应用程序具有默认数据,例如用户类型.什么是迁移后管理默认数据的最有效方法.

它需要处理诸如添加新表之后的情况,它会为其添加默认数据.

dur*_*enk 39

您需要创建一个空的迁移文件,并在操作块中执行您的操作,如文档中所述.

数据迁移

除了更改数据库模式之外,您还可以根据需要使用迁移来更改数据库本身中的数据以及模式.

现在,您需要做的就是创建一个新函数并让RunPython使用它

Docs通过一个示例解释了这一点,展示了如何与模型进行通信.

来自Docs

要创建空的迁移文件,

python manage.py makemigrations --empty yourappname
Run Code Online (Sandbox Code Playgroud)

这是如何更新新添加的字段的示例.

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

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):
    initial = True

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

    operations = [
        migrations.RunPython(combine_names),
    ]
Run Code Online (Sandbox Code Playgroud)


Sar*_*iev 13

我想你要找的是fixtures https://docs.djangoproject.com/en/1.10/howto/initial-data/

来自docs

在您首次设置应用程序时,使用硬编码数据预填充数据库有时很有用.您可以通过灯具提供初始数据.

另请阅读https://code.djangoproject.com/wiki/Fixtures

  • 文档与此答案相矛盾:"如果您想自动加载应用程序的初始数据,请不要使用fixture.而是使用RunPython或RunSQL操作为您的应用程序创建迁移." (2认同)
  • 根据我的理解,fixtures 的整个想法是主要为测试准备样本数据。这与为新表定义一些永久默认/系统/特殊记录无关,就像 OP 所要求的那样。 (2认同)

Bin*_*ati 5

接受的答案很好。但是,由于OP在添加新行而不更新现有条目的上下文中提出了问题。这是用于添加新条目的代码段:

from django.db import migrations


class Migration(migrations.Migration):

    dependencies = [
        ('loginmodule', '0002_login_avatar'),
    ]

    def insertData(apps, schema_editor):
     Login = apps.get_model('loginmodule', 'Login')
     user = Login(name = "admin", login_id = "admin", password = "password", email = "admin@pychat.com", type = "Admin", avatar="admin.jpg")
     user.save()


    operations = [
        migrations.RunPython(insertData),
    ]
Run Code Online (Sandbox Code Playgroud)