1. 讓指定字段按照給定的值進行排序
```?
temp_query= db.session.query(TemplateBuild).filter(
? ? TemplateBuild.deploy_id== deploy_id,
? ? TemplateBuild.env.in_(envs),
? ? TemplateBuild.delete== 0
).order_by(case(value=TemplateBuild.env, whens={'prod': 1, 'staging': 2, 'test': 3, 'dev': 4}))
# 多不同字段排序
# order_by(case(
#? ? (
#? ? ? ? (TemplateDeploy.name == 'prod', 1),
#? ? ? ? (TemplateDeploy.env == 'staging', 2),
#? ? ? ? (TemplateDeploy.compiled == 'Server', 3)
#? ? ))
# )
```
原文鏈接:https://blog.csdn.net/u010311062/article/details/76268783
最近項目中用了Sqlalchemy orm岖圈,開始數(shù)據(jù)不多的時候用coun()函數(shù)不會慢,但是當數(shù)據(jù)到百萬級的時候宫纬,filter_obj.count()來獲取數(shù)據(jù)總數(shù)此叠,就明顯感覺慢了隙弛。
看官方API的描述:
count ( )
Return a count of rows this Query would return.
This generates the SQL for this Query as follows:
SELECT count(1) AS count_1 FROM (
? ? SELECT <rest of query follows...>
) AS anon_1
這里會臨時建一個表把數(shù)據(jù)查詢出來然后在count
我在數(shù)據(jù)庫中對這種count的計時比較:
那么我們?nèi)绾谓鉀Q這個問題呢尚卫。
我們可以利用func.count來處理統(tǒng)計總數(shù)的
這里要用到Sqlalchemy的函數(shù)with_entities來重置查詢
意思就是我們可以這樣做
filter_obj = session.quert(User).filter(User.id>23)
data = filter_obj[0:10]
total = filter_obj.with_entities(func.count(User.id)).scalar()
然而還有一個問題。我這里已經(jīng)將查詢封裝在框架里面了法挨。我并不能保證每個model的主鍵都是id
所以,這里要獲取到傳進來的model的主鍵
from sqlalchemy import inspect
ins = inspect(self.model)
pk = ins.primary_key[0] ? ? ??
primary_key返回的是一個元組拉岁,我們這里支取第一個坷剧,此時pk返回的是Column類型惰爬,('Tuple of primary keys: ', (Column('id', Integer(), table=<cmdb_port_scan>, primary_key=True, nullable=False),))
這里我們將查詢改為filter_obj.with_entities(func.count(pk)).scalar()即可
————————————————
版權聲明:本文為CSDN博主「moses濤」的原創(chuàng)文章喊暖,遵循CC 4.0 BY-SA版權協(xié)議,轉(zhuǎn)載請附上原文出處鏈接及本聲明撕瞧。
原文鏈接:https://blog.csdn.net/u010311062/article/details/76268783