Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
makemigration - Create model and insert data only once

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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),
    ]
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!