Problem:
- I've created a new field named "new_field" in my model MyModel, created migration "01" which added this field. After that I want to change model records with respect to some old field "old_field" in new migration "02"
- So I've created migration "02" which changes my records using RunPython, it might look like this:
.
from ..models import MyModel
def update_model():
for record in MyModel.objects.all():
record.new_field = record.old_field
record.save()
class Migration(migrations.Migration):
dependencies = [('myapp', '01')]
operation = [migrations.RunPython(update_model, lambda *args: None)]
This migration will run fine, but after that I want to create new field "super_new_field":
- I'm creating migration "03" which creates new field "super_new_field"
Everything will be fine. But if I'll clear database and then run migrations, migration "02" will not work since it's trying to access MyModel which does have field "super_new_field" in Django, but it's still missing in database since migration "03" was not executed yet. This means this code in "def update_model" has to be removed (or order of migration and everything else must be changed) in order for migrations to be executed on new enviroments, which is not good
Question:
Is there a way to update model records inside migrations and avoid this problem? Migrations seems to be a nice place to do this since I need to update records just once after migrations were executed, but if I'll create new field and migration then previous migrations which are trying to access model records will not work since field is missing.
Aucun commentaire:
Enregistrer un commentaire