python全棧023 排序

2021-10-10 05:44:41 字數 2265 閱讀 9381

1.order_by:可以指定根據這個表中的某個字段進行排序,如果在前面加了乙個-,代表的是降序排序。

2.在模型定義的時候指定預設排序:有些時候,不想每次在查詢的時候都指定排序的方式,可以在定義模型的時候就制定排序的方式。

3.正向排序和反向排序:預設情況是從小到大,從前到後排序的,如果想要反向排序,可以呼叫排序的字段的desc方法。

例子:

from sqlalchemy import create_engine

from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy import column,integer,string,decimal,boolean,enum,datetime,text,foreignkey

from sqlalchemy.orm import sessionmaker,relationship

hostname = '127.0.0.1'

database = 'class'

port = 3306

username = 'root'

password = 'root'

db_url = 'mysql+pymysql://{}:{}@{}:{}/{}'.format(username,password,hostname,port,database)

engine = create_engine(db_url)

base = declarative_base(engine)

class article(base):

__tablename__ = 'article'

id = column(integer,primary_key=true,autoincrement=true)

title = column(string(50))

def __str__(self):

return 'article(name:%s)'% self.title

# base.metadata.create_all()

session = sessionmaker(bind=engine)

session = session()

新增資料:

# 預設是公升序

article = session.query(article).order_by(article.id).all()

for item in article:

print(item)

執行**:

article = session.query(article).order_by(article.id.desc()).all()

for item in article:

print(item)

執行**:

article = session.query(article).order_by(-article.id).all()

for item in article:

print(item)

執行**:

class article(base):

__tablename__ = 'article'

id = column(integer,primary_key=true,autoincrement=true)

title = column(string(50))

'order_by' : -id

}def __str__(self):

return 'article(name:%s)'% self.title

article = session.query(article).all()

for item in article:

print(item)

09 排序1 排序

09 排序1 排序 25 分 給定n 個 長整型範圍內的 整數,要求輸出從小到大排序後的結果。本題旨在測試各種不同的排序演算法在各種資料情況下的表現。各組測試資料特點如下 include include includeusing namespace std const int cutoff 1000...

09 排序1 排序

n個 長整型範圍內的 整數,要求輸出從小到大排序後的結果。資料2 11個不相同的整數,測試基本正確性 資料3 10 3個隨機整數 資料4 10 4個隨機整數 資料5 10 5個隨機整數 資料6 10 5個順序整數 資料7 10 5個逆序整數 資料8 10 5個基本有序的整數 資料9 10 5個隨機正...

09 排序1 排序

本題旨在測試各種不同的排序演算法在各種資料情況下的表現。各組測試資料特點如下 資料1 只有1個元素 資料2 11個不相同的整數,測試基本正確性 資料3 103個隨機整數 資料4 104個隨機整數 資料5 105個隨機整數 資料6 105個順序整數 資料7 105個逆序整數 資料8 105個基本有序的...