What i need is to get a migration describing the current structure in db and not what i defined in my models file because my models are not aligned to the structure of db, so i would like to get the current status and then apply my modifies defined in my models and make them aligned. Is it possible? And how?
Asked
Active
Viewed 992 times
0
-
what do you mean by that `my models are not aligned to the structure of db` ? – Satendra Nov 09 '17 at 11:52
-
in my models could be tables with a different structure from the actual db, the state i want to bring to my database from the current state – Giuseppe Nov 09 '17 at 12:00
-
possible duplicate of https://stackoverflow.com/questions/1179469/is-it-possible-to-generate-django-models-from-the-database – Satendra Nov 09 '17 at 12:05
-
that talk about model, i talk about migrations – Giuseppe Nov 09 '17 at 14:12
-
Why do your models have a different structure than the database? – Antonis Christofides Nov 09 '17 at 15:20
-
1Do you mean you're trying to create a django app to use an already existing database that wasn't created using django migrations? Meaning you'd like to generate a migration that would create the db at its current state? – dirkgroten Nov 09 '17 at 16:28
-
exactly what you said @dirkgroten, and then apply the modifies from my model that has modifies to apply because of a previous process of continuous intergation that force me on not keeping old migration files – Giuseppe Nov 09 '17 at 17:12
1 Answers
1
Django-admin has a command to create models from a database: inspectdb
. You can find the documentation here.
The idea would be to:
- first generate the initial models using
inspectdb
, - review the result and change field types as needed, if you know better,
- then run
makemigrations
to get the migrations for your current db and - then start modifying your models (to what you have currently in your app) and
- run
makemigrations
again.
It's a fairly complex operation, the recommended approach is to have two databases and move the data from the first to the new one. Django will add lots of tables to your db and you probably don't want this on your legacy db. This is nicely described in this blog post

dirkgroten
- 20,112
- 2
- 29
- 42
-
1That's a possible way, but inspectdb need a manual inspection because not 100% reliable, so it can't be used into an automated process – Giuseppe Nov 10 '17 at 08:23
-
You'll always to do manual work, unfortunately, to integrate a legacy DB in a django app. I don't think this can be reliably automated. And since it's a one-off thing, I don't see why that's a problem – dirkgroten Nov 13 '17 at 09:26