Search code examples
pythondjangodatabasepostgresqlinspectdb

strange migration from django to postgres DB. How to save an exist data


I have walking on a strange way, but it is result of circumstances. I had to been generate single models.py from exist postgres DB by inspect_db. Next I fix some field (was a few problem with keys), and create 2 apps inside this project. So now I have 3 models.py (them are split models.py, whitch was generate by inspect_db). managed = True was added. Classes have same links and datatypes like in the database Next I wish to integrate this models to exist database. I make migration, I migrate and in the end DB have only system django tables (auth_, django_migrations etc.) None from my classes (although migrate files were create). So I tryied to delete migrations catalogs and repeat makemigrations and migrate, but terminal threw it:

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  No migrations to apply.
(forest-venv) user@user-HP-Z800-Workstation ~/MyProjects/forest-venv/lesoved $ python manage.py runserver 8001
Performing system checks...

If I try make migrates again - no changes. I tryied to delete info about my apps in django_migrations table - no result.

So my questions: - It is possible to integrate new models into exist database (if names, keyes and formats is ok)? - Integration is possible by the way where data from exist database is saved after migrations? - How to return possobillity of make migrations? now it isn't work.


Solution

  • The trick when using an existing database is to make sure you start from a well-defined state: First get Django to the exact same state as your db, and only after that start making changes to your models. So these are the steps:

    1. Check that your database doesn't have a django-migrations table, delete it using SQL if needed. (Note: I'm assuming this db isn't generated by Django to start with and you're creating a fresh django application)
    2. Create your models with inspectdb. If needed, rename the models to have proper CamelCase. If you rename models or fields that would change the table or column name in the db, make sure to set db_table (Meta options of your model) and db_column (as field attribute).
    3. Run manage.py makemigrations. Check the migration files for your models, just to be sure the names match with your db.
    4. For your own apps, run manage.py migrate <app> --fake. This will add the migrations to django-migrations table in your db as if they ran, without actually running them.
    5. Then run manage.py migrate to create the django provided tables (auth, contenttype, session etc...)
    6. Now you are at the state where you can start changing things. If you change the model and run makemigrations it should create a migration just for your changes.