在 SQLAlchemy 的一对多关系中,使用 ForeignKey()
来表示表的外键,relationship()
表示表与表之间关联的属性。
完整例子:
from sqlalchemy import create_engine, MetaData
from sqlalchemy import Table, Column, Date, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base # 用于创建基础类
from sqlalchemy.orm import sessionmaker # 用于创建 session
from sqlalchemy.orm import relationship # 建立表与表之间的关系
# 连接数据库
engine = create_engine('sqlite:///school.db', echo=False)
# 基础类
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()
# 用户类(父类)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50))
fullname = Column(String(50))
password = Column(String(12))
def __repr__(self):
return self.name
# 邮箱地址类(子类)
class Address(Base):
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
email_address = Column(String, nullable=False)
user_id = Column(Integer, ForeignKey('users.id')) # 外键
# 定义 Address 的 user 属性,指明二者间关系
user = relationship("User", back_populates="addresses")
def __repr__(self):
return self.email_address
# 定义 User 的 addresses 属性,指明二者间关系
User.addresses = relationship(
"Address",
order_by=Address.id,
back_populates="user"
)
# 创建表
Base.metadata.create_all(engine)
新表创建好之后,我们创建一个新 user 并且为他添加上 address:
jack = User(name='jack', fullname='Jack Bean', password='gjffdd')
jack.addresses = [
Address(email_address='jack@google.com'),
Address(email_address='j25@yahoo.com')
]
session.add(jack)
session.commit()
执行完上述代码后,可以看到除了 users 表添加了 jack 以外,addresses 表也被添加了与 jack 对应的两条记录。
我们现在查询 jack 的 addresses:
jack = session.query(User).\
filter_by(name='jack').one()
print(jack.addresses)
# 执行结果
[jack@google.com, j25@yahoo.com]
反过来从 addresses 查询 user:
address = session.query(Address).\
filter(Address.email_address=='jack@google.com').one()
print(address.user)
# 执行结果
jack
修改某个邮箱地址的用户:
address = session.query(Address).\
filter(Address.email_address=='jack@google.com').one()
ed = session.query(User).\
filter(User.name=='ed').one()
address.user = ed
session.commit()
print(address.user)
# 执行结果
ed