makemigration -只创建模型并插入数据一次



我有一个模型如下:

from django.db import models
class Country(models.Model):
cid = models.SmallAutoField(primary_key=True)
label = models.CharField(max_length=100)
abbr = models.CharField(max_length=3)
countries = {
"AFG": "Afghanistan",
"ALB": "Albania",
"DZA": "Algeria",
"ASM": "American Samoa",
"AND": "Andorra",
"AGO": "Angola",
"AIA": "Anguilla"
};

for c in countries:
row = Country(label = countries[c], abbr = c)
row.save()

现在每当我运行以下命令:

python manage.py makemigrations

第一次,它创建表并填充它。第二次、第三次等等,它一直插入相同的数据(我肯定会多次使用makemigration命令,所以我不希望每次运行命令时都插入数据)

有什么办法做到这一点吗?创建和插入一次?

您可以添加创建数据的数据迁移,这些迁移将在应用迁移时运行一次。这是一个将数据迁移添加到迁移的示例,该迁移还添加了模型

from django.db import migrations, models
countries = {
"AFG": "Afghanistan",
"ALB": "Albania",
"DZA": "Algeria",
"ASM": "American Samoa",
"AND": "Andorra",
"AGO": "Angola",
"AIA": "Anguilla"
}

def create_countries(apps, schema_editor):
Country = apps.get_model('myapp', 'Country')
for c in countries:
Country.objects.create(label=countries[c], abbr=c)

class Migration(migrations.Migration):
dependencies = [
('myapp', '0000_previous'),
]
operations = [
migrations.CreateModel(
name='Country',
fields=[
('cid', models.SmallAutoField(primary_key=True, serialize=False)),
('label', models.CharField(max_length=100)),
('abbr', models.CharField(max_length=3)),
],
),
migrations.RunPython(create_countries),
]

相关内容

  • 没有找到相关文章

最新更新