四十二:数据库之SQLAlchemy之数据查询懒加载技术
时间:2021-07-01 10:21:17
帮助过:17人阅读
from sqlalchemy import create_engine, Column, Integer, String, Float, Text, ForeignKey, DateTimefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy.orm import sessionmaker, relationship, backref# 数据库信息host = ‘127.0.0.1‘port = ‘3306‘database = ‘db_to_sqlalchemy‘username = ‘root‘password = ‘123456‘# 数据库类型+连接数据库的插件,这里使用的pymysqlDB_URI = f‘mysql+pymysql://{username}:{password}@{host}:{port}/{database}‘engine = create_engine(DB_URI) # 创建引擎Base = declarative_base(engine) # 使用declarative_base创建基类session = sessionmaker(engine)()class User(Base): __tablename__ = ‘user‘ id = Column(Integer, primary_key=True, autoincrement=True) username = Column(String(50), nullable=False)class Article(Base): __tablename__ = ‘article‘ id = Column(Integer, primary_key=True, autoincrement=True) title = Column(String(50), nullable=False) create_time = Column(DateTime, nullable=False, default=datetime.now) uid = Column(Integer, ForeignKey(‘user.id‘)) author = relationship(‘User‘, backref=backref(‘article‘, order_by=create_time)) def __repr__(self): return f‘title: {self.title}、create_time: {self.create_time}‘Base.metadata.drop_all() # 删除所有表Base.metadata.create_all() # 创建表user = User(username=‘aaa‘)for x in range(100): article = Article(title=f‘title{x}‘) article.author = user session.add(article)session.commit()


默认返回的是list对象

指定懒加载属性lazy=‘dynamic‘

返回的是AppendQuery对象

导入看源码


以上可以看出,返回的对象会有AppendQuery和Query的全部特性,即可以使用Query的方法进行数据二次过滤
如,查user表第一条数据对应在article表里面所有数据的id大于95的数据

有AppendQuery特性,也就是说可以添加数据


lazy支持的参数
首先,默认的是select

支持的参数



select:如果没有调relationship对应的字段,则不会获取多的这一边的数据,一旦调用此属性,则获取所有对应的数据,返回列表
immediate:不管是否调用relationship对应的字段,都会则获取所有对应的数据,返回列表
joined:将relationship对应的字段查找回来的数据,通过join的方式加到主表数据中
subquery:子查询的方式
四十二:数据库之SQLAlchemy之数据查询懒加载技术
标签:四十二 rem immediate art datetime 通过 ref mysql ons