python中SQLAlchemy排序的坑

高洛峰
Lepaskan: 2017-02-27 09:44:26
asal
1794 orang telah melayarinya

前言

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()
Salin selepas log masuk

不坑的代码

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()
Salin selepas log masuk

对,你没看错,就是那个横杠,拉慢速度。改成 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()
Salin selepas log masuk

更多python中SQLAlchemy排序的坑相关文章请关注PHP中文网!

Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan