[英]Django : How can I put the initial data into database by editting migrations file?
[英]Django:How do I put the initial data into the database before Migrate?
从现有代码添加了模型。 在迁移已添加的模型时,我想输入初始数据。
python3 -m pip安装sqlparse
python3 manage.py makeemigations sbimage
//我已经编辑了生成的0002文件。
python3 manage.py迁移映像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');"),
]
您可以使用django固定装置将初始数据提供给数据库。 这对于您的情况非常有用。
我认为您不应该使用裸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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.