Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

124
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda