SQLAlchemy 關聯表刪除實驗

2022-03-15 19:57:36 字數 2544 閱讀 2868

本實驗所用****於官網文件

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 "" % ( 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 "" % 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

SQLAlchemy 關聯表刪除實驗

本實驗所用 於官網文件 from sqlalchemy import table,column,integer,string,foreignkey from sqlalchemy.orm import relationship,backref from sqlalchemy.ext.declarat...

SQLAlchemy 使用 二 表關聯

在上一章中我們介紹了 sqlalchemy 建立基本表,但是一般情況下,表之間是有關聯的,比如 一對一 一對多 多對多,當然 sqlalchemy 是支援建立model時指定關係的 我們建立兩個表,vip和vip info,邏輯應該是一對一,我們先測試一對多 class vip base vip使用...

sqlalchemy的關聯子查詢

sqlalchemy也算是用過好幾年了,不過一直都用著其中相對簡單的一小部分,最近寫個程式碰到個問題,需要作乙個關聯子查詢,類似這樣的sql語句 select master.select count from detail where detail.parentid master.id and de...