浅析python中SQLAlchemy排序的一个坑
时间:2021-01-06 11:23:16|栏目:Python代码|点击: 次
前言
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代码
下一篇:Python编程实现删除VC临时文件及Debug目录的方法
本文标题:浅析python中SQLAlchemy排序的一个坑
本文地址:http://www.codeinn.net/misctech/41405.html