[Solved]-Django.db.utils.IntegrityError: FOREIGN KEY constraint failed

6👍

The error is in the line:

order = Order.objects.create(user=user, customer_name=name, customer_phone=phone, status_id=1)


You have to pass a status instance for the field status because it is a ForeignKey field. Just setting status_id to an integer won’t work.

I stand corrected, it can work; see this post.

Your error probably happens because either user (or user_id) or status (or status_id) are referencing instances that don’t exist in the related database table.

Are you sure that there is a status with pk=1? Does the operation Status.objects.get(pk=1) succeed?

👤Ralf

3👍

Try setting the named parameter of db_constraint of models.ForeignKey() to False(by default its True) like this:

status = models.ForeignKey(Status, on_delete=models.PROTECT,db_constraint=False)

This worked for me on a certain project the only issue will be that you will be unable to ensure the integrity of your db (e.g knowing whether all the Status objects referenced actually exist) but it makes sense if you’re working with legacy code.
Hope it helps.

👤ang

1👍

I see you didn’t save the instance “order”. —- order.save()

I think the solution is to save instaces to be saved.

Today, I had the same error message as you did. I realized that I forgot to save an instance in my code.
My code is different from your code, but I think you’re worth trying

0👍

I had this problem, because I used the wrong form.
Check your code for the form. I don’t see where do you use it after if form.is_valid(): check.

👤Chris

0👍

I got this error, I forgot to migrate the model when I passed the post instance to the comment model, and before that the instance was Articles

Leave a comment