user3475724
user3475724

Reputation:

Integrity error: update or delete violates foreign key constraint. Django + PostgreSQL

This my UserProfile modification

 class UserProfile(models.Model):
        user = models.OneToOneField(User)
        fb_id = models.IntegerField(primary_key=True,null=False,blank=True)
        follows = models.ManyToManyField('self', related_name='followed_by', symmetrical=False)
    User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])

I am receiving the following error after trying to delete all test users or any single of them.

    django.db.utils.IntegrityError: update or delete on table "blog_userprofile" violates foreign key constraint "blog_from_userprofile_id_a482ff43f3cdedf_fk_blog_userprofile_id" on table "blog_userprofile_follows"
DETAIL:  Key (id)=(4) is still referenced from table "blog_userprofile_follows".

Cascade deleting shall be true by default, why I am receiving this and how can I fix? I am using PostgreSQL + Django 1.8

EDIT: Little prerequisite: I'v changed primary_key from default to fb_id. And there were duplicates, because it was not set unique. So this error is raised when I try to migrate/makemigrations/syncdb :

   django.db.utils.IntegrityError: could not create unique index "blog_userprofile_fb_id_ce4e6e3086081d4_uniq"
DETAIL:  Key (fb_id)=(0) is duplicated.

That is the reason why I tried to delete all test users

And when I tried to reset everything, I tried to get back to default primary key, I receive :

django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "blog_userprofile"

Upvotes: 9

Views: 4418

Answers (2)

copie
copie

Reputation: 1

if you previously used a Mysql database and changed to Postgres, you might run into this issue. You need to delete the migration folder in all applications and then do a fresh "makemigrations" and "migrate" to start your database afresh with postgres worked for me!

Upvotes: -1

Mateus Padua
Mateus Padua

Reputation: 193

After many tests and i figure out that my constraint was without the options Deferrable and Deferred assigned, because my current DB PostgreSQL was migrate from MySQL. Then I assigned this options manually on DB and worked.

enter image description here

More information about this options on the link bellow: Deferrable check constraint in PostgreSQL

I hope this can help.

Upvotes: 4

Related Questions