简单的例子这里已经有了
中文
这里记录一下平时我遇到的一些问题
一对多
需求:一个问题对应多个回复
下面给出代码(字段不完整)
class Questions(db.Model):
__tablename__ = 'questions'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50), nullable=False)
content = db.Column(db.Text, nullable=False)
def __init__(self,title,content):
self.title = title
self.content = content
def __repr__(self):
return "<Questions %r>" % self.title
class Replies(db.Model):
__tablename__ = 'replies'
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.Text, nullable=False)
question_id = db.Column(db.Integer, db.ForeignKey('questions.id',
ondelete="CASCADE"))
replies = db.relationship('Questions',
backref=db.backref('replies',
cascade='all,delete-orphan',
lazy='dynamic',
order_by='Replies.time')
)
def __init__(self, content):
self.content = content
def __repr__(self):
return "<Replies %r>" % self.content
会发现这样的两行(虽然实际上有好几行)
question_id = db.Column(db.Integer, db.ForeignKey('questions.id',
ondelete="CASCADE"))
replies = db.relationship('Questions',
backref=db.backref('replies',
cascade='all,delete-orphan',
lazy='dynamic',
order_by='Replies.time')
)
question_id为外键,关联着questions这个数据表
replies这一行我习惯用反代,也就是backref=db.backref
调用
question = Questions.query.filter_by(id=1).first()
print(question.replies) # 输出该问题的回复
print(question.replies.content) # 错误
for reply in question.replies:
print(reply.content) # 正确
reply = Replies.query.filter_by(id=1).first()
print(reply.question_id) # 输出该回复的所属问题
print(reply.question_id.title)
级联删除
也就是删除一个问题,也会将该问题下的所有回复删除,而删除问题下的回复将不会影响到具体问题
具体请google sqlalchemy cascade
经过测试,上面代码可级联删除回复,而不是将外键置空