8👍
✅
Safest way that I always do is:
- create another field with
field_name_new = models.PositiveIntegerField()
- migrate this new field on production db
- do data migration (convert
field_name
value and move the
converted value to fieldfield_name_new
) - change your code so that
field_name_new
is used - deploy the step 4
- delete the field
field_name
- migrate the step 6 on production db and deploy it (the step 6)
there is only one bad side: you may loose some data in steps 4 and 5. but you can replicate these data to new field basically
32👍
In the past, I’ve always done this with the help of Djangos RunPython operation. Create a custom migration that handles the following.
- Change name of field.
- Add new field of desired type.
- RunPython to handle the logic of converting from one to the other.
- Delete old field.
def migrate_time_to_positive_int(apps, schema_editor):
MyModel = apps.get_model('myapp', 'MyModel')
for mm in MyModel.objects.all():
field_old_time = mm.field_name_old
field_new_int = field_old_time.total_seconds() / 60
mm.field_name = field_new_int
mm.save()
class Migration(migrations.Migration):
operations = [
migrations.RenameField(
model_name='mymodel',
old_name='field_name',
new_name='field_name_old',
),
migrations.AddField(
model_name='mymodel',
name='field_name',
field=models.PositiveIntegerField(),
),
migrations.RunPython(migrate_time_to_positive_int),
migrations.RemoveField(
model_name='mymodel',
name='field_name_old',
)
]
field_name_old.total_seconds() / 60 might need to be adjusted, but you get the idea.
- How do I call a model method in django ModelAdmin fieldsets?
- DRF – How to handle exception on serializer create()?
- Fabric – sudo -u
- Django: correctly retrieve data where date and time are greater than now
- Provide tab title with reportlab generated pdf
Source:stackexchange.com