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://'
engine = create_engine(DB_CONNECT_STRING, echo=False)
DB_Session = sessionmaker(bind=engine)
session = DB_Session()
Base.metadata.create_all(engine)
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)
session.delete(zhangsan)
res = session.query(User).filter_by(name='张三').count()
print(res)
res = session.query(Address).filter(Address.email_address.in_(['[email protected]', '[email protected]'])).count()
print(res)