【Flask】Sqlalchemy limit, offset slice操作

### limit、offset和切片操作:
1. limit:可以限制每次查询的时候只查询几条数据。
2. offset:可以限制查找数据的时候过滤掉前面多少条。
3. 切片:可以对Query对象使用切片操作,来获取想要的数据。可以使用`slice(start,stop)`方法来做切片操作。也可以使用`[start:stop]`的方式来进行切片操作。一般在实际开发中,中括号的形式是用得比较多的。示例代码如下:

 1 # coding:utf-8
 2 
 3 from datetime import datetime
 4 from sqlalchemy import create_engine, Column, Integer, String, DateTime
 5 
 6 from sqlalchemy.ext.declarative import declarative_base
 7 from sqlalchemy.orm import sessionmaker, relationship, backref
 8 
 9 HOSTNAME = '127.0.0.1'
10 PORT = 3306
11 DATABASE = 'sqlalchemy_first'
12 USERNAME = 'root'
13 PASSWORD = '123456'
14 
15 DB_URI = 'mysql+pymysql://{username}:{password}@{host}:{port}/{dbname}?charset=utf8'.format(
16         username=USERNAME, password=PASSWORD, host=HOSTNAME, port=PORT, dbname=DATABASE
17 )
18 engine = create_engine(DB_URI)
19 Base = declarative_base(engine)
20 Session = sessionmaker(engine)
21 session = Session()
22 
23 
24 class Article(Base):
25     __tablename__ = 'article'
26     id = Column(Integer, primary_key=True, autoincrement=True)
27     title = Column(String(50), nullable=False)
28     createtime = Column(DateTime, nullable=False, default=datetime.now)
29 
30     def __repr__(self):
31         return "Article<title:{}>".format(self.title)
32 
33 
34 Base.metadata.drop_all()
35 Base.metadata.create_all()
36 
37 for _ in xrange(100):
38     article = Article(title='article{}'.format(_))
39     session.add(article)
40 session.commit()
41 
42 
43 # limit
44 articles = session.query(Article).limit(10).all()
45 print articles
46 
47 # offset
48 articles = session.query(Article).offset(10).limit(10).all()
49 print articles
50 
51 # slice, sliece(start, end) 从start取到end.
52 articles = session.query(Article).slice(10, 20).all()
53 print articles
54 
55 
56 # 切片
57 articles = session.query(Article)[0:10]
58 print articles

 

posted @ 2018-04-10 22:50  小小易拉罐  阅读(7455)  评论(0编辑  收藏  举报