在Mysql中,外键可以让表之间的关系更加紧密。⽽SQLAlchemy同样也⽀持外 键。通过ForeignKey类来实现,并且可以指定表的外键约束
建立约束
# User / Article
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
username = Column(String(50))
def __str__(self):
return "User(username:%s)" % self.username
class Article(Base):
__tablename__ = 'article'
id = Column(Integer, primary_key=True)
title = Column(String(50))
content = Column(Text, nullable=False)
# 表中的字段
uid = Column(Integer, ForeignKey('user.id', ondelete='CASCADE'))
外键约束有以下项:
1. RESTRICT :父表数据被删除,会阻止删除。默认就是这⼀项。
2. NO ACTION :在MySQL中,同 RESTRICT 。
3. CASCADE :级联删除
4. SET NULL :父表数据被删除,子表数据会设置为NULL。 (推荐)
CURD
# 1.ORM 增加user、article表中的数据
# user = User(username='ecithy')
# session.add(user)
# session.commit()
#
# article = Article(title='python', content='xxxx', uid=1)
# session.add(article)
# session.commit()
# 2.ORM 删除user表中的数据
# user = session.query(User).first()
# print(user.username)
# session.delete(user)
# session.commit()
# 3.外键的查询
# article = session.query(Article).first() # SELECT * FROM article
# uid = article.uid
# user = session.query(User).get(uid) # SELECT * FROM article WHERE uid = 1
# print(user)
article = session.query(Article).first() # SELECT * FROM article
user = session.query(User).filter(User.id == article.uid) # SELECT * FROM user WHERE user.id = 1
print(user)