Flask-SQLAlchemy精確查詢&模糊查詢---ORM(1)

0.背景知識

students表格

st_id name gender age classID remark
10001 小明 1 18 21 小明是位可愛的孩子
10002 小紅 0 18 22 小紅是位聰明的孩子
10003 大牛 1 19 21 大牛是位勇敢的孩子
10004 花花 0 17 22 花花是位懂事的孩子
10005 tony 1 20 23 tony來自美國
10006 古天樂 1 22 21 黑馬王子
10007 陳道明 1 23 22 不是所有牛奶都叫特侖蘇

1.精確查詢

1.單條件–精確查詢


from db_modules import Students
from flask_restful import reqparse, Resource


class StudentsAPI(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument("st_id", type=str)
        self.parser.add_argument("name", type=str)
        self.parser.add_argument("classID", type=str)
        self.parser.add_argument("remark", type=str)

    def get(self):
        args = self.parser.parse_args()

        key_st_id = args.st_id
        key_name = args.name
        key_classID = args.classID
        key_remark = args.remark

        all_results = Students.query.filter_by(classID=key_classID).all()

        data_list = list()
        if all_results:
            for i in all_results:
                dict_one = i.to_dict()
                print(dict_one, "--------")
                data_list.append(dict_one)

            value_msg = "success"
        else:
            value_msg = "couldn't search any infomation"

        result = {

            "status": 200,
            "msg": value_msg,
            "result": data_list

        }
        return result
        

輸入的內容爲:http://127.0.0.1:5000/student?classID=21


{
status: 200,
msg: "success",
result: [
			{
			classID: 21,
			gender: "1",
			st_id: 10001,
			remark: "小明是位可愛的孩子",
			age: 18,
			name: "小明"
			},
			{
			classID: 21,
			gender: "1",
			st_id: 10003,
			remark: "大牛是位勇敢的孩子",
			age: 19,
			name: "大牛"
			},
			{
			classID: 21,
			gender: "1",
			st_id: 10006,
			remark: "黑馬王子",
			age: 22,
			name: "古天樂"
			}
		]
}

2.多條件–精確查詢

# 只有一行有變化,如下方式查詢即可

all_results = Students.query.filter_by(classID=key_classID, name=key_name).all()

2.模糊查詢

1.單條件–模糊查詢


from db_modules import Students
from flask_restful import reqparse, Resource


class StudentsAPI(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument("st_id", type=str)
        self.parser.add_argument("name", type=str)
        self.parser.add_argument("classID", type=str)
        self.parser.add_argument("remark", type=str)

    def get(self):
        args = self.parser.parse_args()

        key_st_id = args.st_id
        key_name = args.name
        key_classID = args.classID
        key_remark = args.remark

        all_results = Students.query.filter(
            Students.remark.like("%" + key_remark + "%") if key_remark is not None else ""
        ).all()

        data_list = list()
        if all_results:
            for i in all_results:
                dict_one = i.to_dict()
                print(dict_one, "--------")
                data_list.append(dict_one)

            value_msg = "success"
        else:
            value_msg = "couldn't search any infomation"

        result = {

            "status": 200,
            "msg": value_msg,
            "result": data_list

        }
        return result


瀏覽器輸入:http://127.0.0.1:5000/student?remark=牛奶

{
	status: 200,
	msg: "success",
	result: [
				{
				classID: 22,
				gender: "1",
				st_id: 10007,
				remark: "不是所有牛奶都叫特侖蘇",
				age: 23,
				name: "陳道明"
				}
	]
}

2.多條件–模糊查詢


 all_results = Students.query.filter(
     Students.st_id.like("%" + key_st_id + "%") if key_st_id is not None else "",
     Students.name.like("%" + key_name + "%") if key_name is not None else "",
     Students.remark.like("%" + key_remark + "%") if key_remark is not None else "",
     Students.classID.like("%" + key_classID + "%") if key_classID is not None else ""
 ).all()
 

輸入地址:http://127.0.0.1:5000/student?name=明

{
	status: 200,
	msg: "success",
	result: [
			{
				classID: 21,
				gender: "1",
				st_id: 10001,
				remark: "小明是位可愛的孩子",
				age: 18,
				name: "小明"
			},
			{
				classID: 22,
				gender: "1",
				st_id: 10007,
				remark: "不是所有牛奶都叫特侖蘇",
				age: 23,
				name: "陳道明"
			}
			]
}

3.精確 & 模糊混合查詢

1.先精確查詢----再模糊查詢


 all_results = Students.query.filter_by(classID = key_classID).filter(
     Students.st_id.like("%" + key_st_id + "%") if key_st_id is not None else "",
     Students.name.like("%" + key_name + "%") if key_name is not None else "",
     Students.remark.like("%" + key_remark + "%") if key_remark is not None else ""
 ).all()

輸入地址:http://127.0.0.1:5000/student?name=明&classID=24

{
	status: 200,
	msg: "couldn't search any infomation",
	result: [ ]
}

輸入地址:http://127.0.0.1:5000/student?name=明&classID=22

{
	status: 200,
	msg: "success",
	result: [
				{
				classID: 22,
				gender: "1",
				st_id: 10007,
				remark: "不是所有牛奶都叫特侖蘇",
				age: 23,
				name: "陳道明"
				}
	]
}

4.多條件或查詢(or_)


from sqlalchemy import or_   # 這個是需要額外導入的方法


all_results = Students.query.filter(
            or_(Students.st_id.like("%" + key_st_id + "%") if key_st_id is not None else "",
                Students.name.like("%" + key_name + "%") if key_name is not None else "",
                Students.remark.like("%" + key_remark + "%") if key_remark is not None else "",
                Students.classID.like("%" + key_classID + "%") if key_classID is not None else "")
        ).all()

瀏覽器輸入:http://127.0.0.1:5000/student?name=花&st_id=10005&remark=牛奶
多個條件,每個條件單獨滿足即可,最終結果爲所有集合的彙總

{
status: 200,
msg: "success",
result: [
			{
				classID: 22,
				gender: "0",
				st_id: 10004,
				remark: "花花是位懂事的孩子",
				age: 17,
				name: "花花"
			},
			{
				classID: 23,
				gender: "1",
				st_id: 10005,
				remark: "tony來自美國",
				age: 20,
				name: "tony"
			},
			{
				classID: 22,
				gender: "1",
				st_id: 10007,
				remark: "不是所有牛奶都叫特侖蘇",
				age: 23,
				name: "陳道明"
			}
			]
}

參考資料:
https://www.jianshu.com/p/a4de47d668e3

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章