sqlalchemy,排序,python,
后端开发-Python教程
这篇文章主要介绍了关于python中SQLAlchemy排序的一个坑,文中给出了详细的示例代码,需要的朋友可以参考借鉴,感兴趣的朋友们下面来一起学习学习吧。html页面布局源码模板,m1芯片vscode,ubuntu打开盘,tomcat缓存页面刷新,天天python爬虫,php正则在线,seo建站软件怎么样,橙色企业网站源码,华丽低调深蓝色后台dedecms模板lzw
前言php源码全局的php文件,ubuntu断电内核损坏,解压的tomcat无法启动,爬虫随机睡眠,php搭建框架,四川seo排名优化公司推荐lzw
SQLAlchemy是Python编程语言下的一款ORM框架,该框架建立在数据库API之上,使用关系对象映射进行数据库操作,简言之便是:将对象转换成SQL,然后使用数据API执行SQL并获取执行结果。最近在使用SQLAlchemy排序遇到了一个坑,所以想着总结下来,分享给更多的朋友,下面来一起看看吧。流媒体服务器源码下载,ubuntu安装卡在时区,爬虫测试报告,php5.6 php扩展包,云鼎seolzw
坑的代码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 = queryquery_tail = query_tail.join(rvid, UserVideo.vid > rvid.c.rvid).limit(20).all()
【相关推荐】
1. Python免费视频教学
2. Python面向对象视频
3. Python学习手册