浅析python中SQLAlchemy排序的一个坑
作者:Just 做 IT 时间:2023-03-29 10:47:23
前言
SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,简言之便是:将对象转换成SQL,然后使用数据API执行SQL并获取执行结果。最近在使用SQLAlchemy排序遇到了一个坑,所以想着总结下来,分享给更多的朋友,下面来一起看看吧。
坑的代码
query = db_session.query(UserVideo.vid,
UserVideo.uid,
UserVideo.v_width,
UserVideo.v_height,
UserVideo.create_time,
UserVideo.cover,
UserVideo.source_url,
UserVideo.v_type,
UserVideo.category,
User.username,
User.sex,
UserExtraInfo.avatar,
UserExtraInfo.watermark)
query = query.filter(UserVideo.status == 1,
User.uid == UserVideo.uid,
UserExtraInfo.uid == UserVideo.uid)
query = query.filter(UserVideo.status == 1)
query = query.order_by(-UserVideo.vid)
query = query.limit(20).all()
不坑的代码
query = db_session.query(UserVideo.vid,
UserVideo.uid,
UserVideo.v_width,
UserVideo.v_height,
UserVideo.create_time,
UserVideo.cover,
UserVideo.source_url,
UserVideo.v_type,
UserVideo.category,
User.username,
User.sex,
UserExtraInfo.avatar,
UserExtraInfo.watermark)
query = query.filter(UserVideo.status == 1,
User.uid == UserVideo.uid,
UserExtraInfo.uid == UserVideo.uid) # .order_by(UserVideo.vid.desc()).limit(20).all()
query = query.filter(UserVideo.status == 1)
query = query.order_by(UserVideo.vid.desc())
query = query.limit(20).all()
对,你没看错,就是那个横杠,拉慢速度。改成 desc()
函数速度能提高10倍
下面附上一个 sqlalchemy 高性能随机取出若干条数据
query = db_session.query(UserVideo.vid,
UserVideo.uid,
UserVideo.v_width,
UserVideo.v_height,
UserVideo.create_time,
UserVideo.cover,
UserVideo.source_url,
UserVideo.v_type,
UserVideo.category,
User.username,
User.sex,
UserExtraInfo.avatar,
UserExtraInfo.watermark)
query = query.filter(UserVideo.status == 1, User.uid == UserVideo.uid, UserExtraInfo.uid == UserVideo.uid)
rvid = db_session.query(func.round(random.random() * func.max(UserVideo.vid)).label('rvid')).subquery()
query = query.filter(UserVideo.category == category)
query_tail = query
query_tail = query_tail.join(rvid, UserVideo.vid > rvid.c.rvid).limit(20).all()
总结
标签:python,sqlalchemy,排序
0
投稿
猜你喜欢
asp 静态页面的另一种思路
2011-04-08 10:32:00
php5.3 不支持 session_register() 此函数已启用的解决方法
2023-11-16 01:59:39
golang/python实现归并排序实例代码
2023-12-13 04:19:01
SQL Server中应当怎样得到自动编号字段
2009-01-15 12:48:00
python中封装token问题
2022-09-29 01:09:32
Vue+Element自定义纵向表格表头教程
2023-07-02 17:10:38
Python动态可视化模块Pynimate初体验
2021-03-22 16:35:09
深入php内核之php in array
2024-05-13 09:23:55
golang 中signal包的Notify用法说明
2023-07-19 19:06:36
Django项目搭建之实现简单的API访问
2021-05-20 23:21:33
python实现连接mongodb的方法
2022-10-18 08:34:18
JS清空上传控件input(type="file")的值的代码第1/2页
2023-08-13 07:22:28
Python全栈之队列详解
2022-10-12 07:51:33
使用python-cv2实现视频的分解与合成的示例代码
2021-06-21 11:51:46
laravel框架中路由设置,路由参数和路由命名实例分析
2024-06-05 09:43:33
js substr支持中文截取函数代码(中文是双字节)
2024-04-10 10:44:58
asp伪继承初探_实例代码
2011-04-19 10:32:00
教你如何在Pycharm中导入requests模块
2023-05-03 13:10:14
在OpenCV里使用Camshift算法的实现
2023-01-24 20:46:40
asp如何实现歌曲在线点播?
2010-05-19 21:32:00