can you remove old migrations file after changing models location django

88 Views Asked by At

I am currently refactoring a django project. It had a few apps with unrelated models (ex: customer in the product app) that I decided to consolidate into a single core app. I use the third method shown in this article: https://realpython.com/move-django-model/#the-django-way-rename-the-table. Everything worked well and I didn't lose any data, but now I have some empty apps that have a lot of migrations files. I would like to delete those apps to have a cleaner project structure. Would deleting the migrations break everything? I do have multiple backups of the database in case something goes wrong.

1

There are 1 best solutions below

0
nigel239 On

You can delete migration files - if you feel comfortable and have been using django for long enough - it is often nescessary to undo something which hard-fails your django application.

When doing so be mindful that migration history is also stored in the database.

Don't try this without backups.

If you delete migrations/001_initial.py, you must also destroy the corresponding database record for myapp migration 001. There is no undoing this, backup your life! ;)

If you do not delete the migration history (careful!) - django will not send the changes to the database and nothing will happen.

You should not in this case delete ALL migration files in the DB.
What you should do here is:

  1. Delete all migration files in your django app.
  2. Run makemigrations, do NOT migrate - if models go unchanged this is not nescessary.
    If you have changed your models in the meantime, the process gets a whole lot more complicated, and you'll have to look at the docs.
  3. Delete the corresponding database records for the application's migration files. All of them (FOR YOUR APPLICATION myapp) - yes.
  4. Run python ./manage.py migrate myapp --fake

What might be a more safe method is to reverse the migrations. I cannot attest to how this works, I have never tried it. https://docs.djangoproject.com/en/5.0/topics/migrations/#reversing-migrations

This command instantly undo's ALL the migrations for your application.

python manage.py migrate myapp zero