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

173
Vistas
How to duplicate field value during migration?

I had a model that only stored a single value:

 class Number(models.Model):
     id = models.AutoField(primary_key=True, unique=True)

Now I want to change the behavior so the number I need is not unique anymore.

class Number(models.Model):
    id = models.AutoField(primary_key=True, unique=True)
    number = models.IntegerField(blank=True)

How to tell the migration to use the ID field as the "one-off value"?

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

The way I do this sort of thing is to add the field like you've already done and run that migration

python manage.py schemamigration your_app --auto
python manage.py migrate your_app

Then you can create a datamigration like so

python manage.py datamigration your_app copy_id_to_number

Then open the migration file that was just created with the above command and change def forward(self, orm) like so

def forwards(self, orm):
    for num in orm.Number.objects.all():
        if num.id:
            num.number = num.id

Then you will want to run this migration

python manage.py migrate your_app
about 4 years ago · Santiago Trujillo Denunciar

0

You need to do this in two migrations. The first one would add the field, with a one-off default of 0. The second one would copy over the values: this could be done with a RunPython function that does something like this:

from django.db.models import F
Number.objects.update(number=F('id'))
about 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