Django 1.7+ migrations: Altering a field to be a ForeignKey

Django 1.7+ migrations: Altering a field to be a ForeignKey

I’m migrating an existing project written in PHP to Django. The existing project is using MySQL and it’s missing some indexes and foreign keys, but there’s also existing data so the normal Django migration file cannot be trusted. I’ll explain why.

Say you have a model like this:

Then you want to change it to be like this:

When you run makemigrations you will get a migrations file that looks like this:

You can clearly see that it first removes the field and then adds it back as a foreign key. This is really bad if you have existing data, because all of that data will be lost. But, thankfully it’s an easy fix. Just modify the RemoveField to be a RenameField and the AddField to be AlterField instead:

Alternatively, you could keep the existing field name as client_id, but then Django will rename the field to client_id_id which might be acceptable for you, but in my case this is unacceptable because the PHP app is still on-line and will be for a long time. Also, there are supplementary services written in other languages that depend on the field name being consistent. 

 Dave

About David Parlevliet

Dave is long time developer with a passion toward teaching. He divides his time between his wife, her cat and his projects. He recently started using twitter so make sure to follow him!