I have a Model
named FooModel
defined in a my_app/models/foo.py
.
After deleting foo.py
, running Django (1.7) migrations raises an error since the old migration files import foo.py
(import myapp.models.foo.FooModel
).
How should I resolve this?
This happens when the model has an ImageField
with an upload_to
parameter.
There are two cases:
You moved FooModel
elsewhere, then edit all your migration files to reflect that move.
You removed FooModel
, in this case, follow these steps:
FooModel
back to where it was.FooModel
elsewhere in your code../manage.py makemigrations my_app
./manage.py squashmigrations my_app <migration created with the previous comand>
— see the doc for more informations on squashing migrations.FooModel
in its migrations.FooModel
and the stale migration files once you ensured everything worked fine.This should work because as FooModel
is not referenced from any other model, it should be removed from the migrations files when squashing them.
However, be warned that squashing migrations is not a simple operation and may have consequences it might be a better idea to just keep the model in your codebase without using it.
Note: in this situation, the object in question is a Django model but this applies to any class, function or module referenced by migration files.
In custom database migrations you should not import your models directly because you can face this particular issue in the future. Instead you should rather use Djangos get_model
function.
MyModel = apps.get_model('myapp', 'MyModel')
for row in MyModel.objects.all():
row.uuid = uuid.uuid4()
row.save(update_fields=['uuid'])
In this case the migrations will also run when you decide to delete the model in the future.
Further read: https://docs.djangoproject.com/en/2.2/howto/writing-migrations/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With