[Answered ]-Migrate data from original User model to Custom User model in django 1.8

2👍

On Postgres, the way Django handles creating unique primary keys for its database records is by using a database sequence from which it gets new primary keys. Looking in my own database, I see that if I have a table named x, then Django creates the sequence under the name x_id_seq. So the sequence for your userauth_userauth table would be userauth_userauth_id_seq.

Now, the way you did your migration you went with raw SQL statements. This completely bypasses Django’s ORM, which means that the sequences for the new tables were not touched by the migration. What you should do after performing such a raw migration is to set the primary key sequence to a number that won’t clash with what is already in the database. Borrowing from this answer, then you should issue:

select setval('userauth_userauth_id_seq', max(id)) 
       from userauth_userauth;

And perform the same kind of operation for the other tables: set their own sequences to the max value if their id field. (If you wonder, the next value that will used will be obtained through nextval and will be equal to one more than the value of the sequence before nextval is called.)

In a comment you wondered why creating new users eventually worked. Probably what happened is that you were trying to create new users and it went like this:

  1. Django got a new primary key from the appropriate sequence. Here the sequence gets incremented.

  2. Django tried to save the new user, which failed because the number it got in the previous step was not unique.

If you do this enough times, your sequence will get incremented for each try because irrespective of transactions, Postgres does not rollback sequences. The documentation says:

Important: Because sequences are non-transactional, changes made by setval are not undone if the transaction rolls back.

So eventually, the sequence increases past the maximum primary key already in the table, and from that point onwards it works.

👤Louis

0👍

What database are you using? It sounds like your database has a counter for the primary key that is generating ids like 3. Since you created new rows with primary keys, you may need to manually reset the DB counter. For an example in postgres, see How to reset postgres' primary key sequence when it falls out of sync?

Leave a comment