Home > Software engineering >  makemigration - Create model and insert data only once
makemigration - Create model and insert data only once

Time:10-17

I've a model as below:

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()

Now whenever I run the following command:

python manage.py makemigrations

The first time, it creates the table and populates it. The 2nd, 3rd and so on times, it keeps inserting the same data (It is definitely possible that I will be using the makemigration command many times, so I don't want it to insert it everytime the command is run)

Any way to achieve this? Create and insert once?

CodePudding user response:

You can add data migrations that create data, these get run once when the migration is applied. This is an example where your data migration is added to the migration that also adds the model

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