简体   繁体   English

Django:如何在迁移之前将初始数据放入数据库中?

[英]Django:How do I put the initial data into the database before Migrate?

Added models from existing code. 从现有代码添加了模型。 I'd like to put in the initial data when I migrate the models I've added. 在迁移已添加的模型时,我想输入初始数据。

python3 -m pip install sqlparse python3 -m pip安装sqlparse

python3 manage.py makeemigations sbimage python3 manage.py makeemigations sbimage

//I have edited the generated 0002 file. //我已经编辑了生成的0002文件。

python3 manage.py Migrate image 0002 python3 manage.py迁移映像0002

//Normal operation confirmed. //确认正常操作。

python3 manage.py sqlmigrate thimage 0002 python3 manage.py sqlmigrate thimage 0002

//Normal operation confirmed. //确认正常操作。

However, the data did not enter the table when the database was verified. 但是,验证数据库后,数据未进入表。

from django.db import migrations, models

class Migration(migrations.Migration):
    dependencies = [
        ('sbimage', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='AuthNumberR',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('auth_number_r', models.CharField(max_length=64)),
            ],
        ),
        migrations.RunSQL("INSERT INTO AuthNumberR (id, auth_number_r) VALUES (2, 'c');"),
    ]

You can use django fixtures to provide initial data to your database. 您可以使用django固定装置将初始数据提供给数据库。 It is quite useful for your case. 这对于您的情况非常有用。

I think you should not use naked SQL queried, instead try using something like this 我认为您不应该使用裸SQL查询,而是尝试使用类似这样的内容

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),
    ]

Reference : https://docs.djangoproject.com/en/2.2/topics/migrations/#data-migrations 参考: https : //docs.djangoproject.com/en/2.2/topics/migrations/#data-migrations

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM