在Mysql中,外键可以让表之间的关系更加紧密。⽽SQLAlchemy同样也⽀持外 键。通过ForeignKey类来实现,并且可以指定表的外键约束

建立约束

  1. # User / Article
  2. class User(Base):
  3. __tablename__ = 'user'
  4. id = Column(Integer, primary_key=True)
  5. username = Column(String(50))
  6. def __str__(self):
  7. return "User(username:%s)" % self.username
  8. class Article(Base):
  9. __tablename__ = 'article'
  10. id = Column(Integer, primary_key=True)
  11. title = Column(String(50))
  12. content = Column(Text, nullable=False)
  13. # 表中的字段
  14. uid = Column(Integer, ForeignKey('user.id', ondelete='CASCADE'))

外键约束有以下项:
1. RESTRICT :父表数据被删除,会阻止删除。默认就是这⼀项。
2. NO ACTION :在MySQL中,同 RESTRICT 。
3. CASCADE :级联删除
4. SET NULL :父表数据被删除,子表数据会设置为NULL。 (推荐)

CURD

  1. # 1.ORM 增加user、article表中的数据
  2. # user = User(username='ecithy')
  3. # session.add(user)
  4. # session.commit()
  5. #
  6. # article = Article(title='python', content='xxxx', uid=1)
  7. # session.add(article)
  8. # session.commit()
  9. # 2.ORM 删除user表中的数据
  10. # user = session.query(User).first()
  11. # print(user.username)
  12. # session.delete(user)
  13. # session.commit()
  14. # 3.外键的查询
  15. # article = session.query(Article).first() # SELECT * FROM article
  16. # uid = article.uid
  17. # user = session.query(User).get(uid) # SELECT * FROM article WHERE uid = 1
  18. # print(user)
  19. article = session.query(Article).first() # SELECT * FROM article
  20. user = session.query(User).filter(User.id == article.uid) # SELECT * FROM user WHERE user.id = 1
  21. print(user)