詹戈:你觉得怎么样在迁移之前,我将初始数据放入数据库?

2024-10-04 11:24:16 发布

您现在位置:Python中文网/ 问答频道 /正文

从现有代码中添加模型。 我想在迁移我添加的模型时输入初始数据。你知道吗

python3 -m pip install sqlparse

python3 manage.py makeemigations sbimage

//我已经编辑了生成的0002文件。你知道吗

python3 manage.py Migrate image 0002

//确认正常运行。你知道吗

python3 manage.py sqlmigrate thimage 0002

//确认正常运行。你知道吗

但是,在验证数据库时,数据没有进入表中。你知道吗

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');"),
    ]

Tags: 数据namepy模型authidtruenumber
2条回答

可以使用django fixtures向数据库提供初始数据。这对你的案子很有用。你知道吗

我认为您不应该使用裸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),
    ]

引用:https://docs.djangoproject.com/en/2.2/topics/migrations/#data-migrations

相关问题 更多 >