I migrated my database from MySql to PostgreSQL, and, as I noticed that many tables weren’t updated, some googling told me to do things like this:
ALTER SEQUENCE my_table_id_seq OWNED BY my_table.id;
and things started to work. I had to do this for all my tables.
Then I realized that after creating a django.contrib.auth.model.User, and trying to create a UserProfile afterwards with a post_save hook, I would get an IntegrityError because the user_id foreign key is sent as null.
Here’s the query and args (in Python) that is sent to PostgreSQL:
INSERT INTO "auth_user" ("username", "first_name", "last_name", "email", "password", "is_staff", "is_active", "is_superuser", "last_login", "date_joined") VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) (u'apitest04', '', '', u'a@a.aa', 'sha1$9f796$69c88c635c8a53a91544765d7996747cf326cfec', False, True, False, u'2013-01-05 12:39:07.384198', u'2013-01-05 12:39:07.384198')
INSERT INTO "myapp_userprofile" ("user_id", "website", "job", "hobbies", "timezone", "about", "company_name", "company_description", "company_website", "retailer_country", "avatar", "default_license", "default_watermark_text", "default_watermark", "default_watermark_position", "default_watermark_opacity", "language") VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) (None, None, None, None, None, None, None, None, None, None, None, 0, None, False, 0, 10, None)
I suppose what’s happening is that the sequence id for auth_user is not advanced before the transaction is closed. I suspect that because the creation of the User is rolled back when the creation of the UserProfile fails, so they must be happening during the same transaction.
Is it possible that the id of the User is somehow not returned yet, because the transaction has not ended yet? And how do you propose I fix the problem?
The problem is solved, and it was happening because the
auth_user.idsequence had no owner. This fixed it: