Gord
Gord

Reputation: 15

Django migrate fails when creating new table

We are fairly new to Django. We we have an app and a model. We'd like to add an 'Category' object to our model. We did that, and then ran 'python manage.py makemigrations'.

We then deploy our code to a server running the older code, and run 'python manage.py migrate'. This throws 2 pages of exceptions, finishing with 'django.db.utils.ProgrammingError: (1146, "Table 'reporting.contact_category' doesn't exist")'

This seems to be looking at our models.py. If we comment out Category from our model, and all references to it, the migration succeeds.

I thought that the point of migrations is to make the database match what the model expects, but this seems to require that the model match the database before the migration.

We clearly are doing something wrong, but what?

Upvotes: 1

Views: 1059

Answers (2)

HuLu ViCa
HuLu ViCa

Reputation: 5450

I believe you skipped some migration in the server, so now you are missing some tables (I have been in that situation. Ensure migrations directories are on your .gitignore. You CAN NOT check in migrations files, you have to run makemigrations on the server). This can be solved by tracing back up to the point the database and models files match, but it is a risky process if it is your production database, so you should make a full backup before proceeding, and try the process on a different computer before.

This would be my advice:

  1. Delete migration files from the server.
  2. Comment the models that rise the error.
  3. Set the server's migration history to the point the database is, using python manage.py makemigrations and python manage.py migrate --fake-initial (this will update the migration files without actually attempting to modify the database).
  4. Uncomment the models that raise the error.
  5. Run python manage.py makemigrations and python manage.py migrate.

If, after you comment the models that raise the exception, you get a different exception, you have to keep on commenting and attempting again. Once a migrations succeeds, you can uncomment all commented models and make an actual migration.

Upvotes: 2

Kareem
Kareem

Reputation: 609

Remember to run python manage.py makemigrations if you made changes to the models.py then run python manage.py makemigrations

Both commands must be run on the same server with the same database

Upvotes: 1

Related Questions