Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda