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

171
Views
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 answers
Answer question

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 Report

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