Django:How 是否在迁移之前将初始数据放入数据库?
Django:How do I put the initial data into the database before Migrate?
从现有代码添加模型。
我想在迁移我添加的模型时输入初始数据。
python3 -m pip install sqlparse
python3 manage.py makeemigations sbimage
//我已经编辑了生成的0002文件。
python3 manage.py Migrate image 0002
//确认正常运行。
python3 manage.py sqlmigrate thimage 0002
//确认正常运行。
但是数据库校验的时候数据没有进入table
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');"),
]
您可以使用 django fixtures 向您的数据库提供初始数据。这对你的情况很有用。
我认为你不应该使用 naked 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
从现有代码添加模型。 我想在迁移我添加的模型时输入初始数据。
python3 -m pip install sqlparse
python3 manage.py makeemigations sbimage
//我已经编辑了生成的0002文件。
python3 manage.py Migrate image 0002
//确认正常运行。
python3 manage.py sqlmigrate thimage 0002
//确认正常运行。
但是数据库校验的时候数据没有进入table
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');"),
]
您可以使用 django fixtures 向您的数据库提供初始数据。这对你的情况很有用。
我认为你不应该使用 naked 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