Sahil
Sahil

Reputation: 1413

Django's --fake-initial doesn't work when migrating with existing tables

I am migrating a project from Django 1.1 to Django 3.0 I am done with the project. When I am dumping the production dump to my local in the newly converted project I get "Table already exists".

Here's what I am doing.

mysql> create database xyx;

docker exec -i <container-hash> mysql -u<user> -p<password> xyx < dbdump.sql

then I run the migrate, as I have had to do some changes to the previously given models.

./manage.py migrate --fake-initial

this is the output I get

    _mysql.connection.query(self, query)
django.db.utils.OperationalError: (1050, "Table 'city' already exists")

So, what to do ?

Upvotes: 1

Views: 1562

Answers (1)

Sahil
Sahil

Reputation: 1413

Alright boys and girls, here's the approach I followed to solve this problem.

I dumped the entire database.

docker exec -i <container-hash> mysql -u<username> -p<password> <dbname> < dump.sql

Now I listed all the migrations I made using

./manage.py showmigrations <app-name>

This will give me the list of all the migrations I have applied, now from inspecting the migrations, I realized that from the 7th migration to the 30th migration I had done my changes.

Here's the tedious part which any sys admin can write a script to do in less than 4 lines of bash script. You can generate the raw SQL of any migration with this command.

./manage.py sqlmigrate <app-name> <migration-name> > changes-i-made.sql

Now that I have created my changes-i-made.sql file I'll need to run this script 22 more times but with >> otherwise everytime you run the command with a single > it will keep overwriting your changes file.

Now once all of your migration changes are recorded inside a file, open up your sql shell connect to the database and start pasting the changes or do some sql magic to pick all the changes directly from the file.

Once you're done go ahead and fake all the migrations, cause you don't need Django to do them you already did.

./manage.py migrate --fake

and then login to your production instance and get ready to fuck with your senior team lead who said you couldn't do it.

I just checked to see if this approach is working and the future migrations will be working, so I created one and everything works like a breeze.

Upvotes: 1

Related Questions