Skip to content

Instantly share code, notes, and snippets.

@cfra
Last active January 10, 2024 19:58
Show Gist options
  • Save cfra/82327629793b841527c5b4994a47d02e to your computer and use it in GitHub Desktop.
Save cfra/82327629793b841527c5b4994a47d02e to your computer and use it in GitHub Desktop.
Django Custom user Model migration path

Steps to migrate existing Django app to new user model

This all refers to PostgreSQL, on other databases it will probably be different.

  1. Create the new User model as an exact copy of django.contrib.auth.models.User (we assume it will be user.User then)

  2. Create the migrations and commit them

  3. Run the following SQL to simulate that the migration has run

    SELECT * FROM django_migrations_id_seq;
    ALTER TABLE django_migrations DROP CONSTRAINT django_migrations_pkey;
    UPDATE django_migrations SET id = id + 1;
    ALTER TABLE django_migrations ADD CONSTRAINT django_migrations_pkey PRIMARY KEY (id);
    INSERT INTO django_migrations (id,app, name, applied) VALUES
       (1, 'user', '0001_initial', '1970-01-01 00:00:00.000000+00');
    ALTER SEQUENCE django_migrations_id_seq RESTART WITH <<<fill-in>>>;
@cfra
Copy link
Author

cfra commented Jan 10, 2024

This leads to issues with the next migrations.

It fails with the unfortunate situation that the migration will be applied but not logged. This can be fixed like this:

INSERT INTO django_migrations (app,name,applied) VALUES ('oauth2_provider', '0001_initial', now());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment