Migrating to a custom user model mid-project in Django 2.2

October 23, 2019

I had to migrate user models to a custom model on Django 2.2 and all of the answers I found required wiping tables or resetting them and re-applying migrations.

Here's I finally did and it's a bit more complicated but it doesn't screw with exisiting data.

1. Create your new app and before doing anything create an initial empty migration with python manage.py makemigrations <myapp> --empty.

2. In the 0001_initial.py file, leave everything blank.

3. Run python manage.py migrate.

4. Now open the django_migrations table in the database and find the <myapp> 0001_initial row (or you can just insert this row).

5. Update the timestamp to equal the initial auth 0001_initial row.

6. Now create your new AbstractUser subclass, set the table name to auth_users, but don't add any new fields yet, and update AUTH_USER_MODEL in your settings

7. Run makemigrations again and copy the operations into 0001_initial.py since this is just a mirror of the auth_user table. Then delete the 0002 migration

8. Now add your custom fields to your model and makemigraions and migrate should work normally.

Without doing it this way django wont allow the database to be migrated because of an InconsitentMigrationHistory error:

django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency <myapp>.0001_initial on database 'default'.

Looking at the django_migrations table we can see the issue is that it was migrated with the initial auth_0001 but changing the AUTH_USER_MODEL updates the swappable dependency making it look for <myapp>.0001_initial which was applied "out of order" because we just created it. Swapping the timesamp makes it all happy.