Question
My User model has a relationship to the Address model. I've specified that the relationship should cascade the delete operation. However, when I query and delete a user, I get an error that the address row is still referenced. How do I delete the user and the addresses?
- class User(db.Model):
- id = db.Column(db.Integer, primary_key=True)
- addresses = db.relationship('Address', cascade='all,delete', backref='user')
- class Address(db.Model):
- id = db.Column(db.Integer, primary_key=True)
- user_id = db.Column(db.Integer, db.ForeignKey(User.id))
- db.session.query(User).filter(User.my_id==1).delete()
How-To
You have the following:
- db.session.query(User).filter(User.my_id==1).delete()
As it says, running delete in this manner will ignore the Python cascade rules that you've set up. You probably wanted to do something like:
- user = db.session.query(User).filter(User.my_id==1).first()
- db.session.delete(user)
沒有留言:
張貼留言