Resetting migrations

Hello,
I am working on a Django app with a postgreSQL database. I had to make several migrations. Unfortunately, most of the migrations files are lost (my mistake).
How could I use the current database schema as the initial one and get rid of all the previous ones which are referenced in the django_migrations table? I would obviously like to keep all the data of my DB.

By the way, there is also something I do not understand: I’ve removed all migrations files from my migrations folder before running a makemigrations command. I’am suprised and confused to find some “add field” in the 0001_initial.py. I was expecting create model only.

Thanks for your help,

Richard

If you know that your models currently match your existing schema, and that there are no generated migrations needing to be accounted for (i.e., you have not created any data migrations or other migrations by hand):

  • Make a backup of everything (including your production database)
  • delete all migration files (but keep the directory and __init__.py files),
  • create a new database
  • change your project to refer to that database.
  • run makemigrations to create a set of migrations describing your current models.
  • change your project to refer back to the original production database
  • empty the django_migrations table from your production database
  • run migrate with the --fake option (this will update the django_migrations table)
  • run showmigrations to verify that all your new initial migrations show as being applied.

Side note: This is basically the process we use to reinitialize our migrations.

<conjecture>
I believe you’ll typically see this with foreign keys to forward references of models. It’s my impression that Django tries to create and apply changes in the order they’re defined in the models.py file, and so if a referenced model hasn’t yet been defined, the ForeignKey field cannot be defined for that model at the time the current model is being defined. Therefore, Django has to go back later to define the FK field for that referencing model.
(I see this a lot in my migrations in this situation, there may be other situations where this is done as well.)
<conjecture>

2 Likes