1

My User model has a relationship to the EmailHistory model. When I try to query and delete a user, I get the error Cannot delete or update a parent row: a foreign key constraint fails. I already specified cascade='all, delete-orphan' in the relationship. How do I delete the related rows when I delete the user?

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    emails = db.relationship('EmailHistory', cascade='all, delete-orphan', backref='user', lazy='dynamic')

class EmailHistory(db.Model):
    id = db.Column(db.Integer, primary_key=True)
davidism
  • 121,510
  • 29
  • 395
  • 339
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • Are you by any chance using MySQL or derivatives and could you post the actual tables with their constraints? What you've configured are the [ORM level cascades](http://docs.sqlalchemy.org/en/latest/orm/cascades.html), which kinda overlap with the DB side constraints. Read the linked docs for proper explanation on the subject. – Ilja Everilä Feb 24 '17 at 18:32
  • From my shell `>>> User.query.filter(id>1).delete()` – Avinash Raj Feb 24 '17 at 19:00
  • think I have to add ondelete option.. – Avinash Raj Feb 24 '17 at 19:01
  • 4
    `user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'), nullable=False)`, solves my problem. – Avinash Raj Feb 24 '17 at 19:06
  • Got similar question and come across this SO thread, @AvinashRaj 's solution works well in my case, but it is weird that `cascade='all, delete'` in `relationship()` does not work as expected . – Ham Nov 16 '21 at 14:51

0 Answers0