SQLAlchemy实现排序有三种方式
一:order_by:查询的时候使用此方式根据某个字段或模型下的属性进行排序
二:模型定义的时候,指定排序方式
三:一对多的时候,relationship的order_by参数
准备工作
from sqlalchemy import create_engine, Column, Integer, String, Float, Text, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship, backref
# 数据库信息
host = ‘127.0.0.1‘
port = ‘3306‘
database = ‘db_to_sqlalchemy‘
username = ‘root‘
password = ‘123456‘
# 数据库类型 连接数据库的插件,这里使用的pymysql
DB_URI = f‘mysql pymysql://{username}:{password}@{host}:{port}/{database}‘
engine = create_engine(DB_URI) # 创建引擎
Base = declarative_base(engine) # 使用declarative_base创建基类
session = sessionmaker(engine)()
class Article(Base):
__tablename__ = ‘article‘
id = Column(Integer, primary_key=True, autoincrement=True)
title = Column(String(50), nullable=False)
create_time = Column(DateTime, nullable=False, default=datetime.now)
def __repr__(self):
return f‘title: {self.title}、create_time: {self.create_time}‘
Base.metadata.drop_all() # 删除所有表
Base.metadata.create_all() # 创建表
article1 = Article(title=‘title1‘)
session.add(article1)
session.commit()
time.sleep(1)
article2 = Article(title=‘title2‘)
session.add(article2)
session.commit()
一:order_by:查询的时候使用此方式根据某个字段或模型下的属性进行排序
默认升序
倒序:desc()
或者使用sqlalchemy.desc
二:模型定义的时候,指定排序方式
升序
倒序
class Article(Base):
__tablename__ = ‘article‘
id = Column(Integer, primary_key=True, autoincrement=True)
title = Column(String(50), nullable=False)
create_time = Column(DateTime, nullable=False, default=datetime.now)
__mapper_args__ = {
‘order_by‘: create_time.desc()
}
def __repr__(self):
return f‘title: {self.title}、create_time: {self.create_time}‘
三:一对多的时候,relationship的order_by参数
class User(Base):
__tablename__ = ‘user‘
id = Column(Integer, primary_key=True, autoincrement=True)
username = Column(String(50), nullable=False)
class Article(Base):
__tablename__ = ‘article‘
id = Column(Integer, primary_key=True, autoincrement=True)
title = Column(String(50), nullable=False)
create_time = Column(DateTime, nullable=False, default=datetime.now)
uid = Column(Integer, ForeignKey(‘user.id‘))
author = relationship(‘User‘, backref=backref(‘article‘, order_by=create_time.desc()))
# __mapper_args__ = {
# ‘order_by‘: create_time
# }
def __repr__(self):
return f‘title: {self.title}、create_time: {self.create_time}‘
升序
若未在backref中指定排序规则,则会找__mapper_args__下的排序规则