Search code examples
djangodjango-migrations

Django migrate won't update my database


Starting from an existing database, I want to update it schema. I change one of my models, then run

python manage.py makemigrations myapp

which creates the migration, defining the new tables and columns correctly. Sample output:

Migrations for 'myapp':
  0001_initial.py:
    - Create model Foo
    - Add field Bar
    - ...

Then I apply the migration:

python manage.py migrate --database mydb

I get this output:

Operations to perform:
  Apply all migrations: admin, myapp, contenttypes, sessions, auth
Running migrations:
  Rendering model states... DONE
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying auth.0007_alter_validators_add_error_messages... OK

It seems to have worked. Git tells me that the sqlite file corresponding to "mydb" has changed. However, instead of having my new tables and columns inside, it just erased the content, leaving empty tables with the old schema.

What am I doing wrong ?


Solution

  • If you have a legacy database without migrations applied you should create initial migrations without any changes. That means that if you changed "models.py" revert it to its original state, then run:

    python manage.py makemigrations myapp
    

    Then run "fake" migrations

    python manage.py migrate --database mydb --fake-initial
    

    After that you can modify your "models.py" and use the normal migrations.