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

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

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 Relatório

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