使用函数
- json_array_elements:将数组拆分为行
- json_array_length:获取数组长度
整体逻辑
需求分析:
- 分页获取图像列表,images字段类型为JSON
- 获取images字段的总长度
实现
sql:
select json_array_elements(images) from target offset 3 limit 3;
select json_array_length(images) from target;
sqlalchemy:
def get_target_images(query: ImageQuery):
offset, limit = get_offset_limit(query.page, query.page_size)
# json_array_elements 将数组拆分为行
image_list = db.session.query(func.json_array_elements(Image.images)).filter(Image.name == query.name).offset(
offset).limit(limit).all()
# json_array_length 获取数组长度
total = db.session.query(func.json_array_length(Image.images)).filter(Image.name == query.name).scalar()
total_page = math.ceil(total / limit)
data = []
for image in image_list:
data.append(image[0])
return response(data=data, total=total, total_page=total_page)