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"?
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
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'))