这个问题纠结了两天了,在往上查了好多,但资料少之又少,没办法,只能自己往根刨,先思考,sqlalchemy的分页是通过方法:paginate,而该方法是在类:BaseQuery即查询结果类中,relatisonship如何才能返回查询结果类呢?去官网查看relationship,他的参数有一个lazy,该lazy主要是设置数据的加载时机和数据方式,如lazy=select,就是访问到该属性时,才会加载该树形数据(X.a)。而查看到属性dynamic时官网描述
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。
啥意思呢?大意是:dynamic重要性主要体现在当数据量较大的时候,如果dynamic,那么relationship的属性返回的是查询对象(query object),这好像与BaseQuery相关,于是亲自动手试试(百看不如一试):
class Tag(Base):
__tablename__ = 'tag'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(100), nullable=False)
state = db.Column(db.Boolean, comment="0:enable; 1:disable")
goodsTypes = db.relationship('GoodsType', secondary=lk_tag_goodstype, lazy='dynamic')
在controller(route定义)模块查询:
tag = Tag.query.get(tag_id)
paginate = tag.goodsTypes.paginate(page=page_num, per_page=data_count)
打印json结果:
{"total": 1, "items": [{"parentId": 0, "state": false, "name": "手机", "unitId":
3, "alert_condition": 2, "createUserId": 1, "updateUserId": 1, "id": 6, "depth": 1, "description": "手机类", "alert_count":
5, "createDate": "2022-06-10 13:29:14", "updateDate": "2022-06-10 13:29:14"}]}



