第一种:字段op是json格式:
{
"uid": "cxb123456789",
"role": 2,
"op_start_time": 1743513707504,
"op_end_time": 1743513707504,
"op_start_id": "op_001",
"op_end_id": "op_002",
"op": {
"ability_node": [{"id": "2c6adc22-e05a-4fe9-835f-ba5d7f8b303", "name": "连接数限制"}],
"skill_node": [{"id": "cvlp6o324te32pj24teg", "name": "yyyy"}],
"knowledge_node": [{"id": "cvlp6o324te32pj24teg", "name": "端到端加密"}],
"op_id": "9131c441-4304-4101-b064-362352d26789",
"op_name": "Initial Data Import",
"pre_op": "",
"next_op": "op_002",
"dep_relationship": "",
"op_result": 1,
"op_score": 95.5,
"op_count": 1
}
}
要求:查询op的json字段里面的op_id为传入的op_id
from sqlalchemy.future import select
db_query = select(KnowledgeAiReport)
op_id = report.op.op_id
db_query = db_query.filter(KnowledgeAiReport.uid == report.uid).filter(KnowledgeAiReport.op.op('->>')('op_id') == op_id)
item = await db_session.execute(db_query)
report_db = item.scalars().first()
第二种:person_type也是json字段,
要求:存储的值是 ["1","2"],要求传入 “1”能查出对应的数据
实现代码:
from sqlalchemy.dialects.postgresql import JSONB # 使用JSONB,因为它支持全文搜索
from sqlalchemy import cast
from sqlalchemy.future import select
db_query = select(TbResident)
db_query = db_query.filter(cast(TbResident.illness_type, JSONB).op('@>')([f'{illness_type}']))
db_query = db_query.offset(page_no * page_size).limit(page_size).order_by(TbResident.created_at.desc())
item = await db_session.execute(db_query)
residents = item.scalars().all()