sqlalchemy和flask-sqlalchemy的幾種分頁方法

來源:互聯網
上載者:User

標籤:ret   位移量   div   set   sql   elf   like   item   state   

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語句,否則報錯

 

 

http://www.cnblogs.com/rgcLOVEyaya/p/RGC_LOVE_YAYA_350days.html

 

sqlalchemy和flask-sqlalchemy的幾種分頁方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.