简述SQLAlchemy中排序的容易犯的一个错误
程序员文章站
2022-05-03 15:18:22
...
这篇文章主要介绍了关于python中SQLAlchemy排序的一个坑,文中给出了详细的示例代码,需要的朋友可以参考借鉴,感兴趣的朋友们下面来一起学习学习吧。
前言
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()
【相关推荐】
1. Python免费视频教程
2. Python面向对象视频
3. Python学习手册
以上就是简述SQLAlchemy中排序的容易犯的一个错误的详细内容,更多请关注其它相关文章!