[Fixed]-Django migration impossible because of bug in field default value?

1๐Ÿ‘

โœ…

why is Django running this โ€œoldโ€ code even if Iโ€™m deleting the model?

Because the model and its method are still referenced in the migration file 0001_initial.py

But when I change the default from fieldA_default to 0, running ./manage.py makemigrations fails because it tries to run the old default value function fieldA_default.

I assume, after you reset the default value on the field, you removed the โ€“ now obsolete โ€“ method fieldA_default. As mentioned above this method is referenced in the initial migration which is now bound to break.

how did I manage to get this invalid code into a migration without Django screaming at me?

When the migration was created, the code wasnโ€™t invalid. Some changes on the model cannot be handled by a simple forward migration. In your case:

  • Deleting the model when it is referenced and imported in a migration file (which in itself is just another python module that cannot just import non-existing classes)

  • same for removing the default method.

One thing you can do when your model code is messed up or out of sync with your migrations/db and makemigrations does not work from the current state, is the following:

  1. python manage.py migrate app_name zero # undo all existing migrations of app
  2. Delete all migration files from the app. Optionally, if you already have valuable data in the db, you can undo them one-by-one and see if step 3. already works

  3. python manage.py makemigrations app_name # new start from clean sheet

This is easy during development and can be considered an alternative to migration squashing, but obviously a last resort if you already have production data in the db. But in that case, one should apply model changes with care and consideration anyway ๐Ÿ™‚

๐Ÿ‘คuser2390182

0๐Ÿ‘

  1. Manually delete all references to Report from your migrations
  2. Delete reports table from DB
  3. Run python manage.py makemigrations. It will create new migration for Report.
  4. Push, deploy.
๐Ÿ‘คDmitry Shilyaev

Leave a comment