zoukankan      html  css  js  c++  java
  • SQLAlchemy的分页操作

    sqlalchemy中使用query查询,而flask-sqlalchemy中使用basequery查询,他们是子类与父类的关系

    假设 page_index=1,page_size=10;所有分页查询不可以再跟first(),all()等

    1.用offset()设置索引偏移量,limit()限制取出量

    db.session.query(User.name).filter(User.email.like('%'+email+'%')).limit(page_size).offset((page_index-1)*page_size)
    #filter语句后面可以跟order_by语句

    2.用slice(偏移量,取出量)函数

    db.session.query(User.name).filter(User.email.like('%'+email+'%')).slice((page_index - 1) * page_size, page_index * page_size)
    #filter语句后面可以跟order_by语句

    注释:此方法和第一种相同的效果。

    因为:由一下内部方法可知,slice()函数第一个属性就是offset()函数值,第二个属性就是limit()函数值

    @_generative(_no_statement_condition)
        def slice(self, start, stop):
            """apply LIMIT/OFFSET to the ``Query`` based on a "
            "range and return the newly resulting ``Query``."""
    
            if start is not None and stop is not None:
                self._offset = (self._offset or 0) + start
                self._limit = stop - start
            elif start is None and stop is not None:
                self._limit = stop
            elif start is not None and stop is None:
                self._offset = (self._offset or 0) + start
    
            if self._offset == 0:
                self._offset = None
    
        @_generative(_no_statement_condition)
        def limit(self, limit):
            """Apply a ``LIMIT`` to the query and return the newly resulting
    
            ``Query``.
    
            """
            self._limit = limit
    
        @_generative(_no_statement_condition)
        def offset(self, offset):
            """Apply an ``OFFSET`` to the query and return the newly resulting
            ``Query``.
    
            """
            self._offset = offset

    3.用paginate(偏移量,取出量)函数,用于BaseQuery

    user_obj=User.query.filter(User.email.like('%'+email+'%')).paginate(int(page_index), int(page_size),False)
    #遍历时要加上items
    object_list =user_obj.items

    4.filter中使用limit

    db.session.query(User.name).filter(User.email.like('%'+email+'%') and limit (page_index - 1) * page_size, page_size)
    #此处不能再跟order_by语句,否则报错
  • 相关阅读:
    HTML5 localStorage and sessionStorage
    WebViewJavascriptBridge-Obj-C和JavaScript互通消息的桥梁
    js控制手机号码中间用星号代替
    无法删除登录名 '***',因为该用户当前正处于登录状态。 (Microsoft SQL Server,错误: 15434)
    在QT中添加LIB的方法
    Android颜色代码
    判断ubuntu是32位还是64位
    Android应用市场App发布
    ubuntu目录结构(转)
    QT调用CHM方法
  • 原文地址:https://www.cnblogs.com/xushuhai/p/8846997.html
Copyright © 2011-2022 走看看