為 `app/api_1_0/controller` 下的 `user.py` 控制器做查詢操作
Flask-SQLAlchemy 在 Model 類上提供了 query 屬性。通過 query 屬性會得到一個所有記錄的查詢對象。在使用 all() 或者 first() 發起查詢。
我們為了看到返回結果,返回數據只能是 `string`,?`dict`,?`tuple`,我們從 `flask` 導入了 `jsonify`
``` Python
from?app.api_1_0?import?bp
from?app.api_1_0.model.user?import?UserModel
from?app?import?db
from?flask?import?jsonify
@bp.route('/user',?methods=['POST'])
def add_user():
pass
@bp.route('/user',?methods=['GET'])
def list_user():
try:
????????user_obj?=?UserModel.query.all()
except Exception as?e:
return '查詢失敗'
????user_list?=?[]
for?user?in?user_obj:
????????user_list.append(user.to_dict())
return?jsonify(user_list)
```
測試

### 其他查詢
**1. 根據條件查詢**
```
# 查詢id為1的記錄
UserModel.query.filter_by(id=1).all()
# 查詢id為1的記錄只取一條
UserModel.query.filter_by(id=1).limit(1).all()
# 查詢符合條件的記錄根據id排序只取2條
UserModel.query.order_by(UserModel.id).limit(2).all()
UserModel.query.order_by(UserModel.id.desc()).limit(2).all()
UserModel.query.filter(UserModel.username.endswith('維奇')).order_by(UserModel.id.desc()).limit(2).all()
UserModel.query.filter(UserModel.username.startswith('阿爾')).order_by(UserModel.id).limit(2).all()
UserModel.query.filter(UserModel.username.contains('爾維')).order_by(UserModel.id).all()
# 查詢符合限制條的第一條
UserModel.query.filter_by(id=2).first()
UserModel.query.filter_by(id=1).first_or_404()
# 根據主鍵查詢
UserModel.query.get(1)
UserModel.query.get_or_404(1)
```
使用 `get_or_404()` 來代替 `get()`,使用 `first_or_404()` 來代替 `first()`,對于不存在的條目返回一個 404 錯誤,而不是返回 None。
**2. 統計符合條件的數量**
```
UserModel.query.filter_by(id=1).count()
```
**3.group分組統計**
根據名字分組,查詢名字,統計同名手機號個數,根據名字分組,原 sql 語句
```
SELECT base_user.username AS base_user_username, count(base_user.mobile) AS count_1
FROM base_user GROUP BY base_user.username
```
用 flask_sqlachemy 表示,返回的是一個 list
```
from sqlalchemy import func
UserModel.query.with_entities(UserModel.username,?func.count(UserModel.mobile)).group_by('username').all()
```
**4.原生查詢**
```
from sqlalchemy import text
UserModel.query.filter(text('id>=:value1?and?id?<:value2')).params(value1=2,value2=5).all()
UserModel.query.from_statement(text("select?*?from?base_user?where?id=:value")).params(value=1).all()
db.session.execute("SELECT COUNT(*) FROM table").scalar() # 返回的數字
```
**4.分頁**
```
UserModel.query.paginate(page, per_page,Error_out)
1. page: 哪一個頁
2. per_page: 每頁多少條數據
3. Error_out: False 查不到不報錯
4. pages: 共有多少頁
5. items: 當前頁數的所有對象
user_obj?=?UserModel.query.paginate(2,2,False)
user_obj.page
user_obj.per_page
user_obj.pages
```
### 查詢條件
**and**
```
from sqlalchemy import and_
UserModel.query.filter(and_(UserModel.username?==?'阿爾維奇',UserModel.id==1)).all()
```
或者
```
UserModel.query.filter(UserModel.username?==?'阿爾維奇',UserModel.id?==?1).all()
```
**or**
```
from sqlalchemy import or_
UserModel.query.filter(or_(UserModel.username == '阿爾維奇', UserModel.username == 'Python')).all()
```
**in**
```
UserModel.query.filter(UserModel.id.in_([1,2])).all()
```
**not in**
```
UserModel.query.filter(~UserModel.id.in_([1,2])).all()
```
**like**
```
UserModel.query.filter(UserModel.username.like('阿爾%')).all()
```