添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
正直的香瓜  ·  Issues with Wifi ...·  1 月前    · 
乖乖的炒面  ·  Scenic Path along ...·  1 月前    · 
鬼畜的大象  ·  wpf ...·  5 月前    · 
本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《 阿里云开发者社区用户服务协议 》和 《 阿里云开发者社区知识产权保护指引 》。如果您发现本社区中有涉嫌抄袭的内容,填写 侵权投诉表单 进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

本实验所用代码来源于 官网文档

from sqlalchemy import Table, Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
'''关联表删除实验'''
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    password = Column(String)
    addresses = relationship("Address", 
                            back_populates='user', 
                            cascade="all, delete, delete-orphan")
    def __repr__(self):
       return "<User(name='%s', fullname='%s', password='%s')>" % ( self.name, self.fullname, self.password)
class Address(Base):
    __tablename__ = 'addresses'
    id = Column(Integer, primary_key=True)
    email_address = Column(String, nullable=False)
    user_id = Column(Integer, ForeignKey('users.id'))
    user = relationship("User", 
                        back_populates="addresses")
    def __repr__(self):
        return "<Address(email_address='%s')>" % self.email_address
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
DB_CONNECT_STRING = 'sqlite://' # 'sqlite:///:memory:'
engine = create_engine(DB_CONNECT_STRING, echo=False)
DB_Session = sessionmaker(bind=engine)
session = DB_Session()
# 1. 创建表
Base.metadata.create_all(engine)
# 2. 插入数据
some_users = [User(id=1, name='张三', password='111111'),
              User(id=2, name='李四', password='222222'),
              User(id=3, name='王五', password='333333'),
              User(id=4, name='赵六', password='444444')]
session.add_all(some_users)
some_addresses = [Address(id=1, email_address='[email protected]', user_id=1),
                  Address(id=2, email_address='[email protected]', user_id=1),
                  Address(id=3, email_address='[email protected]', user_id=2),
                  Address(id=4, email_address='[email protected]', user_id=3),
                  Address(id=5, email_address='[email protected]', user_id=4)]
session.add_all(some_addresses)
session.commit()
#关联表删除实验
zhangsan = session.query(User).get(1)
# 删除!!
del zhangsan.addresses[1]
res = session.query(Address).filter(Address.email_address.in_(['[email protected]', '[email protected]'])).count()
print(res) # 结果为 1
# 删除!!
session.delete(zhangsan)
res = session.query(User).filter_by(name='张三').count()
print(res) # 结果为 0
res = session.query(Address).filter(Address.email_address.in_(['[email protected]', '[email protected]'])).count()
print(res) # 结果为 0