sqlalchemy和flask-sqlalchemy几种分页操作

2018/02/01 17:53
阅读数 3.7K

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

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


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


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


#filter语句后面可以跟order_by语句
db.session.query(User.name).filter(User.email.like('%'+email+'%')).slice((page_index - 1) * 
page_size, page_index * page_size)
注释:此方法和第一种相同的效果。

因为:由一下内部方法可知,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


#此处不能再跟order_by语句,否则报错
db.session.query(User.name).filter(User.email.like('%'+email+'%') and limit (page_index - 1) * 
page_size, page_size)

 

展开阅读全文
打赏
0
1 收藏
分享
加载中
更多评论
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部