#IntegrityError: Foreign Key constraint failed

27 messages · Page 1 of 1 (latest)

dim rune
#

Having a pretty interested error here. Typically when seeing this error I would instantly run and check that all of my ForeignKey fields have on_delete=models.CASCADE and I would find my culprit. I've triple checked, and know for a fact this isn't what is happening. This app is fairly large, so it's too much code to just randomly copy/paste. If anyone who thinks they may be able to help wants to see some specific code, just let me know. But I'm just looking for some general guidance because I'm at a loss.

trim hamlet
#

Is there anyway you're referencing a model that has already been deleted?

#

For example:

author = Author.objects.create(...)
book = Book(author=author, ...)
author.delete()
book.save()
dim rune
#

No, its giving me this error when i try even deleting it using the admin panel. So the only models its referencing are still alive.

#

(or so i assume still alive)

trim hamlet
#

The database error should contain which table is the cause. Unfortunately I don't think Django exposes it.

dim rune
#

Yeah i scoured the error and couldnt find any reference.

trim hamlet
#

Probably the easiest thing to do is to try delete the row using raw SQL and observe the error there.

dim rune
#

😂

trim hamlet
#

Haha, can you connect to your database with another tool? psql or DBeaver for example?

dim rune
#

i do have db browser for sqlite, and havent prepped my db for deployment yet so im still using the default sqlite.

trim hamlet
#

Ah shoot, I just remembered that the CASCADE is handled by Django not by the database. So it wouldn't be very helpful.

dim rune
#

aww dang

#

if you come up with any debugging methods, please let me know ❤️

trim hamlet
#

Are you sure all your migrations have been ran? Maybe there's one with a constraint that is missing.

dim rune
#

yeah i just checked... it's def some specific model. because i just made a new user with none of the added data, and was able to delete it.

#

wondering if these weird ExclusiveForeignKey fields i made are the culprite... It's my first time using them.

trim hamlet
#

🤔 I'm not familiar

#

Sorry, I'm out of ideas 😦

dim rune
#

its all good, i really appreciate the effort!

#

wait! i've got more info!

#

so it only wont allow me to delete the user, if any of the Inherent models are populated.

#

i used abstract inheritance on a couple of the models. and im able to delete the user unless one of those models are populated.

dim rune
#

reworked the models to get rid of any abstract inheratence. still getting the same error 😦

dim rune
#

resolved finally

#

ISSUE: that exclusiveforeignkey in one of my tables creates a kinda circular dependency
SOLUTION: i over rode the delete method in my custom user model to shape the deletion order, thus breaking out of the weird loop.