Reputation: 410652
I'm trying to delete a User
object in a Django app, but I keep getting an IntegrityError
in a related object when deleting the User
. The related object looks like this:
class Unfollowing(models.Model):
source = models.ForeignKey(User, related_name='unfollowings_by')
target = models.ForeignKey(User, related_name='unfollowings_of')
created_on = models.DateTimeField(auto_now_add=True)
But when deleting a User
, I get an error like the following:
IntegrityError: update or delete on table "auth_user" violates foreign key constraint "source_id_refs_id_5b69e09fc6161c2a" on table "core_unfollowing"
DETAIL: Key (id)=(6439) is still referenced from table "core_unfollowing".
What's the deal? Shouldn't the related Unfollowing
objects be deleted automatically when an associated User
is deleted? For what it's worth, I added an explicit on_delete=models.CASCADE
to both Unfollowing.source
and Unfollowing.target
(even though that's the default) and I still got the same error.
Upvotes: 2
Views: 2912
Reputation: 29794
That's weird indeed. Here's a couple of things I would try:
First, did you update the database schema after adding on_delete=models.CASCADE
?. If not, it wouldn't do any effect. You can double check if ON DELETE CASCADE
is activated by dumping the database schema directly, not figuring it out from Django.
Seems to me this is more a db engine related error than Django's. If you're 100% positive ON DELETE CASCADE
is activated in auth_user table and the related tables, then you can try to delete a user directly from your sql client. If it works, and the same user give you trouble from Django (or a similar user, given the fact that you erased the first one), then try to dump the SQL query Django is doing and repeat it from your sql client.
This is the approach I would take. Also, check if this happens with a specific user or every user, check for hanging references in the Unfollowing tables. Maybe also there exist an old table you used to have and that's the one giving you problem.
I'll focus the research directly with the database and a sql client and after I managed to get it working there, move back to Django.
This is more the path I'll follow than an answer since this seems to be a very specific problem.
I hope this might help a little.
Good luck!
Upvotes: 2