前言
一对多关系,当删除主表数据的时候,关联表数据一起删除掉
一对多
模型设计
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
addresses = db.relationship('Address', backref='person', cascade="all,delete")
class Address(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(50))
person_id = db.Column(db.Integer, db.ForeignKey('person.id'))
主要是在 relationship 加一个cascade="all,delete"
属性
其它关联删除方式
### 只删除父级,子不影响
# 1. addresses = db.relationship('Address', backref='person', passive_deletes=True)
### 子级跟随删除
# 2. addresses = db.relationship('Address', backref='person', cascade="all, delete-orphan")
# 3. addresses = db.relationship('Address', backref='person', cascade="all, delete")
## 父级删除,子级不删除,外键更新为 null
# 4. addresses = relationship("Address", backref = backref("child"))
新增与删除
新增数据
person = Person(name='yoyo')
person.addresses = [
Address(email='[email protected]')
]
db.session.add(person)
db.session.commit() # 提交
删除Person 表数据,关联表一并删除
p = Person.query.filter_by(name='yoyo').first()
db.session.delete(p)
db.session.commit()
标签:SQLAlchemy,addresses,删除,Flask,db,person,Address,backref,84
From: https://www.cnblogs.com/yoyoketang/p/16751295.html