limit和offset切片操作

Posted wuheng-123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了limit和offset切片操作相关的知识,希望对你有一定的参考价值。

技术分享图片

#encoding: utf-8

from sqlalchemy import create_engine,Column,Integer,String,Float,func,and_,or_,    DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from random import randint
from datetime import datetime

HOSTNAME = 127.0.0.1

PORT = 3306

DATABASE = first_sqlalchemy

USERNAME = root

PASSWORD = 123456

#dialect+driver://username:[email protected]:port/database
DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/"          "{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE)

engine = create_engine(DB_URI)

Base = declarative_base(engine)

# Session = sessionmaker(engine)
# session = Session()

session = sessionmaker(engine)() #Session(**local_kw)


class Article(Base):
    __tablename__ = article
    id = Column(Integer,primary_key=True,autoincrement=True)
    title = Column(String(50),nullable=False)
    create_time = Column(DateTime,default=datetime.now)

    def __repr__(self):
        return <article:{title}>.format(title=self.title)


# Base.metadata.drop_all()
#
# Base.metadata.create_all()
#
#
# for x in range(0,100):
#     article = Article(title = ‘title%s‘%x)
#     session.add(article)
# session.commit()


#第一limit的用法,限制查询多少数据
article = session.query(Article).limit(10).all()#用limit限制只查询10个数据
print(article)

#第二个参数offset的用法,本意是偏移量,在这里就是从多少开始查询
article_offset = session.query(Article).offset(10).all()
print(article_offset)

#offset和limit联合起来用,就相当于python 的字符串和列表、元祖的切片操作
article_offset_limit = session.query(Article).offset(10).limit(5).all()
print(article_offset_limit)

#如果查询最新的10篇文章,就可以用order_by 和 limit 一起用
article_order_by_limit = session.query(Article).order_by(Article.id.desc()).limit(10).all()
print(article_order_by_limit)

#slice,本身就是切片的意思
article_order_by_slice = session.query(Article).order_by(Article.id.desc()).slice(0,10).all()
print(article_order_by_slice)

#还有一个更简单的方法,就想python的列表切片操作

article_list_slice = session.query(Article).order_by(Article.id.desc())[0:10]
print(article_list_slice)

 

以上是关于limit和offset切片操作的主要内容,如果未能解决你的问题,请参考以下文章

04 Django模型层: Django-model进阶

重修课程day61(django之补充)

07.Django学习之model进阶

DAY19-Django之model进阶

Django_model进阶

Django 模型系统(model)&ORM--进阶