zoukankan      html  css  js  c++  java
  • sqlalchemy和flask-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语句,否则报错
  • 相关阅读:
    线程池的爆掉
    WebApi的调用-1.前端调用
    使用SqlSugar 4.X的T4生成实体类
    JSON.NET 空值处理, 数字转字符,时间格式化
    C#获取路径
    MVC4 下DropDownList使用方法(转)
    14.并发与异步
    14.并发与异步
    14.并发与异步
    VS2013 生成时复制文件或目录到指定目录
  • 原文地址:https://www.cnblogs.com/rgcLOVEyaya/p/RGC_LOVE_YAYA_350days.html
Copyright © 2011-2022 走看看