Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django "Cannot add or update a child row: a foreign key constraint fails"

I have a model Coupon, and a model Photo with a ForeignKey to it:

class Photo(models.Model):     coupon = models.ForeignKey(Coupon,                                related_name='description_photos')     title = models.CharField(max_length=100)     image = models.ImageField(upload_to='images') 

I set up inlines in the admin so now I'm able to add photos to a coupon from the admin.

I attempt to add one, and upload is successful, but then I get Django's debug page with this error:

IntegrityError at /admin/coupon/coupon/321/ (1452, 'Cannot add or update a child row: a foreign key constraint fails (`my_project`.`coupon_photo`, CONSTRAINT `coupon_id_refs_id_90d7f06` FOREIGN KEY (`coupon_id`) REFERENCES `coupon_coupon` (`id`))') 

What is this and how can I solve this problem?

(If it matters, this is a MySQL database.)

EDIT: I tried it on an Sqlite3 database that has a slightly different dataset, and it worked, so perhaps there's loose data in my current DB? How can I find it and delete it?

like image 231
Ram Rachum Avatar asked May 30 '11 16:05

Ram Rachum


People also ask

How do you solve Cannot add or update a child row a foreign key constraint fails?

The problem occurs because you set the foreign key in child table after you insert some data in the child table. Try removing all the data from child table, then set the foreign key and afterwards add/insert the data in table, it will work.

Why do foreign key constraints fail?

The error comes when you are trying to add a row for which no matching row in in the other table. “Foreign key relationships involve a parent table that holds the central data values, and a child table with identical values pointing back to its parent. The FOREIGN KEY clause is specified in the child table.

Can we update foreign key in a table?

The foreign key relation can be created either through SSMS GUI or T-SQL. Rules for update/delete operations may be specified explicitly. However if nothing is specified then the default rule is No Action. The rule may be changed to any other option at any time later by recreating the FK relation.

What is child row?

This child rows are attached to each parent row, and can be used, for example, to provide extra information about the parent row, or an editing form. The child rows will always be placed immediately after a parent row (if the child rows are designated to be visible, using the row(). child.


1 Answers

Some of my tables were in InnoDB and some were in MyISAM... I changed everything to MyISAM and the problem was solved.

like image 56
Ram Rachum Avatar answered Oct 18 '22 15:10

Ram Rachum