0

This is only happening to me when I try to update anything via the django admin site. Otherwise I have no problems. The error I am getting is:

IntegrityError at /admin/ledger/user/1/
duplicate key value violates unique constraint "ledger_googleprofile_user_id_key"
DETAIL:  Key (user_id)=(1) already exists.

Here is what my google profile model looks like:

#ledger.models
class GoogleProfile(models.Model):
    plus_id = models.CharField(max_length=2000, null=True, blank=True)
    info = JSONField(null=True, blank=True)
    youtube_info = JSONField(null=True, blank=True)
    user = models.ForeignKey('User', related_name='google_profile', blank=True, null=True)

I've tried running python manage.py sqlsequencereset ledger and then pasting that into psql, but that isn't solving the problem. It's weird because even users that don't have a GoogleProfile associated with them still throw this error when trying to save in the admin.

Any ideas on what the problem could be. I would rather not have to delete my production database and start over...

After writing this out I think the problem might be because the GoogleProfile.user field may have been a oneToOne before. I am not positive but I think it was a oneToOne that I changed to a ForeignKey (many to one) which would explain why there are problems with a unique constraint. But should running manage.py makemigrations and migrate solve the problem? Any idea how to solve this manually?

Chase Roberts
  • 9,082
  • 13
  • 73
  • 131

1 Answers1

3

To remove the constraint manually, run the following to double check the constraint name:

SELECT *
FROM information_schema.constraint_table_usage
WHERE table_name = 'ledger_googleprofile';

Then

ALTER TABLE ledger_googleprofile DROP CONSTRAINT constraint_name;

Given the error you've posted I'd guess the actual SQL is that below, but I'd run the SELECT query just to double check:

ALTER TABLE ledger_googleprofile DROP CONSTRAINT ledger_googleprofile_user_id_key;
justcompile
  • 3,362
  • 1
  • 29
  • 37
  • I figured out that I needed to just remove the constraint, but I couldn't figure out how to get the name of the constraint. You were right, it was istting in front of me the whole time 'ledger_googleprofile_user_id_key'. Thanks. – Chase Roberts Jan 03 '15 at 21:45
  • Had been struggling to fix this. Thank you. – SuperNova Mar 22 '18 at 17:12