文章内容

2022/2/8 10:45:28,作 者: 黄兵

sqlalchemy.exc.ArgumentError: For many-to-one relationship,级联删除,cascade

最近在修改 SQLAlchemy 模型的时候,使用级联删除出现了如下错误:

sqlalchemy.exc.ArgumentError: For many-to-one relationship Receive.phone_number_list, delete-orphan cascade is normally configured only on the "one" side of a one-to-many relationship, and not on the "many" side of a many-to-one or many-to-many relationship.  To force this relationship to allow a particular "PhoneNumberList" object to be referred towards by only a single "Receive" object at a time via the Receive.phone_number_list relationship, which would allow delete-orphan cascade to take place in this direction, set the single_parent=True flag. (Background on this error at: https://sqlalche.me/e/14/bbf0)


出现问题的原因:
对于关系 <relationship>,delete-orphan 级联通常只配置在一对多关系的“one”端,而不是多对一或多对多的“many”端关系。
具体示例可以参考下面的资料。


解决方案:

将级联删除设置在 “one” 端,而不是 “many” 端,具体可以参考下面的参考资料部分。

下面是一个设置级联删除的典型例子:

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))

如果需要删除 User,使用下面查询:

user = db.session.query(User).filter(User.my_id==1).first()
db.session.delete(user)



参考资料:

1、For relationship , delete-orphan cascade is normally configured only on the “one” side of a one-to-many relationship, and not on the “many” side of a many-to-one or many-to-many relationship.

2、SQLAlchemy delete doesn't cascade

分享到:

发表评论

评论列表