时间:2021-07-01 10:21:17 帮助过:2人阅读
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__下的排序规则
四十:数据库之SQLAlchemy实现排序的三种方式
标签:ons 根据 创建 username 参数 text from 实现 art