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

Ram Rachum picture Ram Rachum · May 30, 2011 · Viewed 27.1k times · Source

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?

Answer

Ram Rachum picture Ram Rachum · May 30, 2011

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