当前位置:首页 >> 脚本专栏

浅析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()

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。