Dariush
Dariush

Reputation: 483

How to make the initial migration for a DB that diverged from the corresponding models?

Situation: a project I'm working in had a file corruption or something. Models are the latest version, but the SQLite DB had to be rolled back before some columns were added/removed/modified. Migration files are all gone. Trying to create migrations anew results in the new columns being present in the initial migration file, so I can neither migrate for real (due to the table existing) nor fake it (since the columns are missing in the DB).

Given those circumstances, how can I make an initial migration matching the columns currently present in the DB so I can fake it and then make a real second migration to bring the tables in line with the models? The only thing that comes to mind is manually tweaking the models to match the DB schema, making the initial migration, faking it and then restoring the new version of the models, but I'd much prefer having this done automatically.

Upvotes: 1

Views: 95

Answers (1)

e4c5
e4c5

Reputation: 53744

django inpsectdb to the rescue.

But first, learn how to use git if you had used proper version control, you would not be facing this difficulty now.

  1. First step, add the code to version control.

  2. Delete the existing models files

  3. Use inspectdb to generate a models.py from the tables in the database. This is not perfect, you will have to edit the file manually and you may have to spread it out between different models files manually.

  4. Now delete the contents of the migrations table

  5. do a ./manage.py makemigrations (yourapp)

  6. Do the fake migration you mentioned

  7. replace the generated models.py with your current models.py (a git checkout of that file will do the trick nicely)

  8. do a makemigrations and migrate again.

good luck.

Upvotes: 1

Related Questions