SQLAlchemy 的惰性查询



Flask中的Sqlalchemy, 很多人对数据库关系db.relations()时里面的lazy这个参数很模糊。

比如说,在一对多模型中:back回复-comment评论(一个回复可以有多个评论)

外键(多方):comment_id = db.Column(db.Integer, db.ForeignKey("info_comment.id"))

关系属性(一方):back_list=db.relationship('Comment',lazy='dynamic',backref='comment')

这个里面就用到了lazy='dynamic'

什么意思呢?在官方文档中,我把英文翻译成中文:

dynamic表示在访问属性的时候,并没有在内存中加载数据,而是返回一个query对象, 需要执行相应方法才可以获取对象,比如.all().下面结合实例解释这几个的使用场景。

班级与学生:

students = db.relationship('Student', backref='_class', lazy="dynamic")#放在一方的关系属性

>>> from app.models import Student as S, Class as C

>>> s1=S.query.first()

>>> c1=C.query.first() #班级对象

>>> c1.students #班级对象对应的学生,是一个query对象

>>> c1.students.all()#使用.all()才出来具体的学生对象

[, , ]

讲到这里应该懂了吧,

其实lazy属性默认的是lazy="select",它默认返回最终结果,等同于上面的.all()

最终要说的是:lazy是用在一对多的一和多对多 非中间表 中的,这只是lazy的两个属性,还有另外两个,总共四个属性


看下官方说明吧:

lazy 决定了 SQLAlchemy 什么时候从数据库中加载数据:,有如下四个值:(其实还有个noload不常用)

select: (which is the default) means that SQLAlchemy will load the data as necessary in one go using a standard select statement.

joined: tells SQLAlchemy to load the relationship in the same query as the parent using a JOIN statement.

subquery: works like ‘joined’ but instead SQLAlchemy will use a subquery.

dynamic : is special and useful if you have many items. Instead of loading the items SQLAlchemy will return another query object which

you can further refine before loading the items. This is usually what you want if you expect more than a handful of items for this relationship

你可能感兴趣的:(SQLAlchemy 的惰性查询)