【问题标题】:makemigration - Create model and insert data only oncemakemigration - 创建模型并只插入一次数据
【发布时间】:2021-12-04 09:16:13
【问题描述】:

我有一个模型如下:

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

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

有什么方法可以做到这一点?创建并插入一次?

【问题讨论】:

  • 它不会在每次迁移时运行,它会在每次启动 Django 进程时运行。
  • 哦..那更糟了...有什么办法可以防止这种情况发生吗?我在文档中看到与 migrations.RunPython 相关的内容,但很难理解

标签: python python-3.x django


【解决方案1】:

您可以添加创建数据的data migrations,这些会在应用迁移时运行一次。这是一个示例,您的数据迁移被添加到同时添加模型的迁移中

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

【讨论】:

  • 谢谢。让我试试看。这是我一直在努力解决的问题 - Country = apps.get_model('myapp', 'Country') 不确定如何包含模型
猜你喜欢
  • 2018-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多