import psycopg2 import json import sys sys.stdout.reconfigure(encoding="utf-8") conn = psycopg2.connect( host="192.168.110.252", port=15432, database="postgresql", user="postgresql", password="Jchl1528", ) cursor = conn.cursor() cursor.execute("SET search_path TO hisdev, public") print("=" * 80) print("修复手术医嘱 content_json 为 null 的问题") print("=" * 80) print() # 1. 查询所有 content_json 为 null 的手术医嘱 cursor.execute(""" SELECT id, prescription_no, content_json FROM wor_service_request WHERE category_enum = 4 AND delete_flag = '0' AND content_json IS NULL """) rows = cursor.fetchall() print(f"发现 {len(rows)} 条 content_json 为 null 的手术医嘱") print() # 2. 从对应的手术申请单获取 desc_json 并更新 cursor.execute(""" SELECT sr.id, sr.prescription_no, rf.desc_json FROM wor_service_request sr JOIN doc_request_form rf ON rf.prescription_no = sr.prescription_no WHERE sr.category_enum = 4 AND sr.delete_flag = '0' AND sr.content_json IS NULL AND rf.delete_flag = '0' """) fix_rows = cursor.fetchall() print(f"找到 {len(fix_rows)} 条可以修复的记录") print() # 3. 更新 content_json update_count = 0 for row in fix_rows: service_id = row[0] prescription_no = row[1] desc_json = row[2] if desc_json: try: # 解析 desc_json if isinstance(desc_json, str): desc_data = json.loads(desc_json) else: desc_data = desc_json # 构建 content_json content_data = { "surgeryName": desc_data.get("surgeryName", ""), "surgeryCode": desc_data.get("surgeryCode", ""), "surgeryFee": desc_data.get("surgeryFee", "0"), "anesthesiaFee": desc_data.get("anesthesiaFee", "0"), "plannedTime": desc_data.get("plannedTime", ""), "surgeryIndication": desc_data.get("surgeryIndication", ""), "preoperativeDiagnosis": desc_data.get("preoperativeDiagnosis", ""), } content_json = json.dumps(content_data, ensure_ascii=False) # 更新数据库 cursor.execute( """ UPDATE wor_service_request SET content_json = %s WHERE id = %s """, (content_json, service_id), ) update_count += 1 print(f"✓ 更新 ID={service_id}, 单号={prescription_no}") except Exception as e: print(f"✗ 更新失败 ID={service_id}: {e}") conn.commit() print() print(f"✓ 成功修复 {update_count} 条记录") print() # 4. 验证修复结果 cursor.execute(""" SELECT id, prescription_no, content_json FROM wor_service_request WHERE category_enum = 4 AND delete_flag = '0' AND content_json IS NULL """) remaining = cursor.fetchall() print(f"剩余 {len(remaining)} 条 content_json 为 null 的记录") cursor.close() conn.close() print() print("=" * 80) print("修复完成!请刷新医嘱列表页面查看效果。") print("=" * 80)